3
votes

I'm new to unix socket programming. I have some questions about unix sendto() function.

ssize_t sendto(int sockfd,
               const void *buf,
               size_t len,
               int flags,
               const struct sockaddr *dest_addr,
               socklen_t addrlen);

My questions are:

(1) If port number in dest_addr is not set, how would the receiver host deal with the packet?

(2) How does this functions process info in dest_addr? I send IPv6 packet with this function, I have to use sockaddr_in6 struct which is a totally different with sockaddr_in struct:

struct sockaddr_in {
    short            sin_family;   // e.g. AF_INET, AF_INET6
    unsigned short   sin_port;     // e.g. htons(3490)
    struct in_addr   sin_addr;     // see struct in_addr, below
    char             sin_zero[8];  // zero this if you want to
};

struct sockaddr_in6 {
    u_int16_t       sin6_family;   // address family, AF_INET6
    u_int16_t       sin6_port;     // port number, Network Byte Order
    u_int32_t       sin6_flowinfo; // IPv6 flow information
    struct in6_addr sin6_addr;     // IPv6 address
    u_int32_t       sin6_scope_id; // Scope ID
};

and why do we need a cast to struct sockaddr in sendto()? Looks like only sa_family is meaningful to this function. Then what about other fields?

1

1 Answers

2
votes

Regarding 1: there is no special "undefined" value. Whatever value happens to be stored in this memory location will be taken as the desired port number.

Regarding 2: each struct sockaddr starts with an address family identifier. If the family is set to AF_INET, all functions will know to expect a struct sockaddr_in. Likewise for the other families. In that sense, I believe the example you posted (which seems to imply AF_INET6 can be a valid value of sin_family in a struct sockaddr_in) to be misleading.