Saturday, 15 June 2013

c - Getting client IP address and port? -



c - Getting client IP address and port? -

i'm writing file sharing programme , jist of there 1 main server clients connect to. however, clients machines hosting files when 1 client requests file another, must create connection it. when client connects main server it's ip , port (i think) with:

int client_len = sizeof(client); int new_sd = accept(sd, (struct sockaddr *)&client, &client_len); char str[inet_addrstrlen]; inet_ntop(af_inet, &(client.sin_addr), str, inet_addrstrlen); //printf("%s\n", str); int port = (int) ntohs(client.sin_port); //printf("port is: %d\n", (int) ntohs(client.sin_port));

the printf's give me 127.0.0.1 , 40xxx. main server using 127.0.0.1 , port 3000. i'm pretty sure have right client ip , port when seek set connection between 2 clients using 127.0.0.1 , 40xxx, not work. connect function keeps returning error. here's code trying found connection between 2 clients:

if ((cd = socket(af_inet, sock_stream, 0)) == -1) { fprintf(stderr, "can't creat socket\n"); exit(1); } bzero((char *)&cserver, sizeof(struct sockaddr_in)); cserver.sin_family = af_inet; cserver.sin_port = htons(cport); if (inet_pton(af_inet, caddress, &cserver.sin_addr) == -1) { printf("inet_pton error occured\n"); exit(1); } /* connecting server */ if (connect(cd, (struct sockaddr *)&cserver, sizeof(cserver)) == -1) { fprintf(stderr, "can't connect server\n"); exit(1); }

cport int while caddress char array.

here's code client attempting create connection incoming connections. code ip address , port homecoming 0.0.0.0 , 0 respectively.

if ((sockfd = socket(af_inet, sock_stream, 0)) == -1) { fprintf(stderr, "can't creat socket\n"); exit(1); } /* bind address socket */ bzero((char *)&clientserver, sizeof(struct sockaddr_in)); clientserver.sin_family = af_inet; clientserver.sin_port = 0; clientserver.sin_addr.s_addr = htonl(inaddr_any); if (bind(sockfd, (struct sockaddr *)&clientserver, sizeof(clientserver)) == -1){ fprintf(stderr, "can't bind name socket\n"); exit(1); } char str[inet_addrstrlen]; inet_ntop(af_inet, &(clientserver.sin_addr), str, inet_addrstrlen); printf("%s\n", str); int clientserverport = (int) ntohs(clientserver.sin_port); printf("port is: %d\n", (int) ntohs(client.sin_port)); /* queue 10 connect requests */ listen(sockfd, 10);

all help appreciated!

you can't utilize client port new connection. port beingness used connect server, it's not listening incoming connections. client needs bind port, hear on it, , send port number you. can send client, , can connect port.

note may not work @ if first client behind nat router. router won't know should forwards new port client. peer-to-peer applications dynamic port numbers impractical when nat involved. instead, should define dedicated port purpose; users can configure port forwarding on routers port.

c sockets client server

No comments:

Post a Comment