开发者

C: socket binding on wrong port

开发者 https://www.devze.com 2023-01-24 09:30 出处:网络
I have C code that listens on a port, but it is listening on the wrong port. This is defined in a .h file:

I have C code that listens on a port, but it is listening on the wrong port.

This is defined in a .h file:

#define PHANTASIA_PORT 2101

The socket:

int the_socket, error, on=1;

    /* create a socket */
errno = 0;
if ((the_socket=socket(AF_INET, SOCK_STREAM, 0)) == -1) {

    sprintf(error_msg,
       "[0.0.0.0:?] Socket creation failed in Do_init_server_socket: %s\n",
       strerror(errno));

    Do_log_error(error_msg);
    exit(SOCKET_CREATE_ERROR);
}

error = setsockopt(the_socket, SOL_SOCKET, SO_REUSEADDR,
        (char *) &on, sizeof(on));

This is how it binds:

    /* set up the bind address */
bind_address.sin_family = AF_INET;
bind_address.开发者_高级运维sin_addr.s_addr = INADDR_ANY;
bind_address.sin_port = PHANTASIA_PORT;

    /* bind to that socket */
error = bind(the_socket, (struct sockaddr *) &bind_address,
        sizeof(bind_address));
error = listen(the_socket, SOMAXCONN);

But then when it is run, lsof reports:

phantasia  2400     root    4u  IPv4 2024436       TCP *:13576 (LISTEN)

When I changed the port to 2100 in the define, it instead listened for:

phantasia  2266     root    4u  IPv4 2021315       TCP *:13320 (LISTEN)

This is some old code but doesn't have any warnings or errors when compiling. Maybe something is going over my head. I have a debug log when it binds and it reports it binds to port 2101.


Replace PHANTASIA_PORT with htons(PHANTASIA_PORT).


Use htons function when specifying the port number.

So this line:

bind_address.sin_port = PHANTASIA_PORT;

Should be:

bind_address.sin_port = htons(PHANTASIA_PORT);

htons is a function that will convert host integer numbers to network integer numbers, fixing the endianness (HI-LO/LO-HI byte order within integer) of them if necessary.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号