can't connect Java client to C server.
- by nexes
I have a very simple server written in C and an equally simple client written in Java. When I run them both on the same computer everything works, but when I try to run the server on computer A and the client on computer B, I get the error IOException connection refused from the java client. I can't seem to find out whats happening, any thoughts? I've even turned off the firewalls but the problem still persists.
server.
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#define PORT 3557
#define BUF 256
int main(int argc, char *argv[])
{
struct sockaddr_in host, remote;
int host_fd, remote_fd;
int size = sizeof(struct sockaddr);;
char data[BUF];
host.sin_family = AF_INET;
host.sin_addr.s_addr = htonl(INADDR_ANY);
host.sin_port = htons(PORT);
memset(&host.sin_zero, 0, sizeof(host.sin_zero));
host_fd = socket(AF_INET, SOCK_STREAM, 0);
if(host_fd == -1) {
printf("socket error %d\n", host_fd);
return 1;
}
if(bind(host_fd, (struct sockaddr *)&host, size)) {
printf("bind error\n");
return 1;
}
if(listen(host_fd, 5)) {
printf("listen error");
return 1;
}
printf("Server setup, waiting for connection...\n");
remote_fd = accept(host_fd, (struct sockaddr *)&remote, &size);
printf("connection made\n");
int read = recv(remote_fd, data, BUF, 0);
data[read] = '\0';
printf("read = %d, data = %s\n", read, data);
shutdown(remote_fd, SHUT_RDWR);
close(remote_fd);
return 0;
}
client.
import java.net.*;
import java.io.*;
public class socket {
public static void main(String[] argv) {
DataOutputStream os = null;
try {
Socket socket = new Socket("192.168.1.103", 3557);
os = new DataOutputStream(socket.getOutputStream());
os.writeBytes("phone 12");
os.close();
socket.close();
} catch (UnknownHostException e) {
System.out.println("Unkonw exception " + e.getMessage());
} catch (IOException e) {
System.out.println("IOException caught " + e.getMessage());
}
}
}