Error in bind() when implementing TCP implementation

I am using the sample TCP sample in order to establish a connection with a TCP server with a certain port number. I checked if the connection is in general is successful or not using telnet open "xx.xx.xx" portnumber which was successful.

In the above sample, the server address was random using 

sin.sin_addr.s_addr = htonl(INADDR_ANY);
 with which the connection was successful,

I replaced it with 

		if (inet_pton(AF_INET, "xxx.xxx.xx.xxx", &sin.sin_addr.s_addr) <= 0) {
        perror("Invalid address");
    }
    	sin.sin_family = AF_INET;
		sin.sin_port = htons(UDP_PORT);

		if (bind(fd, (struct sockaddr *)&sin, sizeof(sin)) < 0) {
			perror("bind");
		}
 

which is causing error   

TCP sample has started
Waiting for network.. OK
Error: bind(): Network is unreachable
exit

I am also attaching my project.

SDK: v2.3.0,actinius icarus, nrf9160 dk as flashing device

Can you tell me what I am doing wrong here?

Parents
  • Hi, I worked on TCP connection with sockets not so long ago, albeit using wifi. I didn't come across the need for using bind() function call. Instead here's a snippet of what I did to make it work: 

    sock = zsock_socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    	if (sock < 0)
    	{
    		LOG_ERR("Error creating socket\n");
    		return -1;
    	}
    
    	// Iterate through until we get a successful connection
    	for (rp = (struct zsock_addrinfo *)results; rp != NULL; rp = rp->ai_next)
    	{
    		if (rp->ai_addr->sa_family == AF_INET)
    		{
    			sa = (struct sockaddr_in *)rp->ai_addr; // IPv4 Address
    			sa->sin_port = htons(HTTP_PORT_NUMBER); // Needs to be a string
    			zsock_connect(sock, (struct sockaddr *)sa, sizeof(struct sockaddr_in));
    			if (sock > 0)
    				break;
    		}
    	}

  • Thank you for the code snippet but I am not understanding if it is taking a specific IP address or is it generating something in the for loop before assigning to sa. If it is the latter then I need a way in which I can I use the IP address that I already have?

    For context I am basing my code on this IBM TCP Server connection

  • iirc I had to resolve domain names to IP addressed first before this step... if you have an IP address I'd suppose that should just work. Interesting, I haven't come across the IBM TCP server setup, I might take a look later today!
    Edit: looks like the same thing was done here? hostnm = gethostbyname(argv[1]);
    -Eric

Reply Children
Related