Find the answer to your Linux question:
Results 1 to 2 of 2
Im still fairly new to sockets in C, so any help appriciated.. Code: void show_error(char *msg, char *func, int line, char *file); int main(int argc, char *argv[]) { struct sockaddr_in ...
Enjoy an ad free experience by logging in. Not a member yet? Register.
  1. #1
    Linux Guru
    Join Date
    Apr 2003
    Location
    London, UK
    Posts
    3,284

    Why does this code not Bind to a TCP port?


    Im still fairly new to sockets in C, so any help appriciated..

    Code:
    void show_error(char *msg, char *func, int line, char *file);
    
    int main(int argc, char *argv[]) {
    
    	struct sockaddr_in inet;
    	int inet_len, inet_sock;
    	
    	if((inet_sock = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
    		show_error("Could not create socket!", __FUNCTION__, __LINE__, __FILE__);
    		return 1;
    	}
    	memset(&inet, 0, sizeof(inet));
    	inet.sin_family = AF_INET;
    	inet.sin_port = htons(9000);
    	
    	if(!inet_aton("127.0.0.23", &inet.sin_addr)) {
    		show_error("error in inet_aton", __FUNCTION__, __LINE__, __FILE__);
    		return 1;
    	}
    	
    	inet_len = sizeof(inet);
    
    	if(bind(inet_sock, (struct sockaddr *)&inet, inet_len) == -1) {
    		show_error("Could not bind()", __FUNCTION__, __LINE__, __FILE__);
    		return 1;
    	}
    	
    	return 0;
    }
    
    void show_error(char *msg, char *func, int line, char *file) {
    
    	printf("Error: %s in %s() on line %d in file %s\n", msg, func, line, file);
    	return;
    }
    Compiles without warnings, executes ok. But doesnt bind?

    Any help?

    Cheers,

    Jason

  2. #2
    Linux Guru
    Join Date
    Apr 2003
    Location
    London, UK
    Posts
    3,284
    ok, found it out...

    needed to call listen() after the bind()

    doh!

    Jason

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •