If the error occurred on bind (this is not so obvious based on your question content, since the error message that you indicate is not displayed in the code), it is probably because the address is not available.
This is usually because it is already in use or not available on the current node.
With a few exceptions, you can only bind to the IP addresses assigned to your local interfaces. You should check that 192.168.1.8 is in this class. This means that 127.0.0.1 will be the local interface (hence why it works), and that INADDR_ANY will work as well - perhaps this is the βaddressβ that you should use if you have no real concrete need to limit the interface itself.
You should check errno after the failure function and match it with capabilities.
As an aside, and this probably has nothing to do with your problem, the way you initialize the sockaddr_in structure (setting fields and then clearing the rest) seems less portable to me.
I think it would be safer to clear the batch, and then just set what you want after that, something like:
memset (&my_addr, 0, sizeof (my_addr)); my_addr.sin_family = AF_INET; my_addr.sin_addr.s_addr = inet_addr (hostname); my_addr.sin_port = htons (5000);
At least the order of the fields in the structure will not affect your code.
You may see a problem with the following code. First of all, the required headers:
#define __USE_GNU #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h>
Then check the arguments and create the sockets.
int main (int argc, char *argv[]) { int sockfd; struct sockaddr_in me; if (argc < 2) { printf ("Need argument with IP address\n"); return 1; } if ((sockfd = socket (AF_INET, SOCK_DGRAM, 0)) == -1) { perror("socket"); return 1; }
Then the binding itself:
memset (&me, 0, sizeof (me)); me.sin_family = AF_INET; me.sin_addr.s_addr = inet_addr (argv[1]); me.sin_port = htons (5000); if (bind (sockfd, (struct sockaddr *)&me, sizeof(struct sockaddr)) == -1) { fprintf (stderr, "errno = %d ", errno); perror("bind"); exit(1); } close(sockfd); return 0; }
When you run this with certain arguments, you can see that it works fine for those where the IP addresses belong to local interfaces ( 127.0.0.1 and 192.168.0.101 ), but not for those that donβt, for example 192.168.0.102 :
pax> ifconfig | grep 'inet addr' inet addr:192.168.0.101 Bcast:192.168.0.255 Mask:255.255.255.0 inet addr:127.0.0.1 Mask:255.0.0.0 inet addr:192.168.99.1 Bcast:192.168.99.255 Mask:255.255.255.0 inet addr:192.168.72.1 Bcast:192.168.72.255 Mask:255.255.255.0 pax> ./testprog 127.0.0.1 pax> ./testprog 192.168.0.101 pax> ./testprog 192.168.0.102 errno = 99 bind: Cannot assign requested address pax> grep '#define.*99' /usr/include/asm-generic/errno.h
And, from the link to the bind man page above, we see:
EADDRNOTAVAIL