I'm trying to get a C Client to connect to a Python server in UNIX/Linux. However, it seems my C Client isn't able to connect to the Python server. I tried running on the localhost, but that didn't seem to work. Hard-coding the hostnames into both the server and the client (to "127.0.0.1") didn't work either.
Here's the code for the Python server:
import socket
import sys
HOST = "127.0.0.1"
PORT = 8888
print("creating socket...")
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print("binding socket...")
try:
s.bind((HOST, PORT))
except socket.error as err:
print("error binding socket, {}, {}".format(err[0], err[1]))
print("successfully bound socket")
s.listen(1)
print("now listening on {}:{}".format(HOST, PORT))
while True:
conn, addr = s.accept()
conn.sendall(str.encode("testing"))
#conn.close()
s.close()
...and here's the code for the C Client:
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
int main(int argc, char** argv) {
if (argc != 3) {
printf("usage: client [HOSTNAME] [PORT]\n");
return 0;
}
const char *hostname = argv[1];
int port = atoi(argv[2]);
int sockfd = 0, n = 0;
char recvBuff[1024];
struct sockaddr_in saddr;
memset(recvBuff, '0', sizeof(recvBuff));
if ( sockfd = socket(AF_INET, SOCK_STREAM, 0) < 0 ) {
fprintf(stderr, "error: could not create socket\n");
return 1;
}
saddr.sin_family = AF_INET;
saddr.sin_port = htons(port);
saddr.sin_addr.s_addr = htonl(hostname);
if ( connect(sockfd, (struct sockaddr_in*)&saddr, sizeof(saddr)) < 0 ) {
fprintf(stderr, "error: could not connect to %s:%i\n", hostname, port);
return 1;
}
while ( n = read(sockfd, recvBuff, sizeof(recvBuff) - 1) > 0 ) {
recvBuff[n] = 0;
if ( fputs(recvBuff, stdout) == "EOF" ) {
fprintf(stderr, "error: fputs\n");
}
printf("\n");
}
return 0;
}
Interestingly enough, I can still connect to the Python server via other means, like telnet, or through this client coded in Python:
import socket
import sys
HOST = "localhost"
PORT = 8888
print("creating socket")
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print("attempting to connect to host")
try:
s.connect((HOST, PORT))
except socket.error as err:
print("error: could not connect to host, {}, {}".format(err[0], err[1]))
sys.exit()
print("successfully connected to host")
data = s.recv(1024)
s.close()
print("The server responded with: {}".format(data))
I assume this is a client-side issue, then, since other methods to connecting to the server seems to work just fine. If that is the case, how would I go about fixing the C Code to connect properly? If that is not the case, could this be an issue pertaining to my network? I tried running in both an Arch VM and my school's IT Servers, and both yielded the same result.