T
tweak
I'm struggling with the concept of typecasting when
setting up a TCP client.
Here's a code snip (modified from W. Richard Stevens Unix Programming
book) to demonstrate where I am struggling:
int sockfd;
struct sockaddr_in servaddr;
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(13); /* PORT 13 */
/* argv[1] = "127.0.0.1" */
if (inet_pton(AF_INET, argv[1], &servaddr.sin_addr)) <= 0 ) {
perror("inet_pton()");
exit(1);
}
if ( (connect(sockfd, (struct sockaddr *) &servaddr, sizeof(servaddr)) <
0) {
perror("connect()");
exit(1);
}
When this line occurs:
(struct sockaddr *) &servaddr
the previously assigned values within servaddr are typecast to struct
sockaddr,
which is defined as:
struct sockaddr {
uint8_t sa_len;
sa_family_t sa_family;
char sa_data[14];
};
My confusion is how sa_data[14] becomes populated. I do not
understand the conversion.
Can anyone help me out?
I stepped through the code creating a pointer of type struct sockaddr
and pointed it to the address of servaddr. But I do not understand
why sa_data[14] would have data looking like \111\0\r\0\0 . . .
nor do I understand how to convert that string back to it's original
form.
Any help would be appreciated.
Thanks,
Brian
P.S. I'm compiling using gcc, and debuggin with gdb.
setting up a TCP client.
Here's a code snip (modified from W. Richard Stevens Unix Programming
book) to demonstrate where I am struggling:
int sockfd;
struct sockaddr_in servaddr;
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(13); /* PORT 13 */
/* argv[1] = "127.0.0.1" */
if (inet_pton(AF_INET, argv[1], &servaddr.sin_addr)) <= 0 ) {
perror("inet_pton()");
exit(1);
}
if ( (connect(sockfd, (struct sockaddr *) &servaddr, sizeof(servaddr)) <
0) {
perror("connect()");
exit(1);
}
When this line occurs:
(struct sockaddr *) &servaddr
the previously assigned values within servaddr are typecast to struct
sockaddr,
which is defined as:
struct sockaddr {
uint8_t sa_len;
sa_family_t sa_family;
char sa_data[14];
};
My confusion is how sa_data[14] becomes populated. I do not
understand the conversion.
Can anyone help me out?
I stepped through the code creating a pointer of type struct sockaddr
and pointed it to the address of servaddr. But I do not understand
why sa_data[14] would have data looking like \111\0\r\0\0 . . .
nor do I understand how to convert that string back to it's original
form.
Any help would be appreciated.
Thanks,
Brian
P.S. I'm compiling using gcc, and debuggin with gdb.