I am confused by this argument to the function which is defined as
int bind(int s, const struct sockaddr *name, int namelen)
and called as
bind(sd, (struct sockaddr_in *) &addr, length);
I'm unable to interpret what struct sockaddr_in *
means here.
Would this work: bind (sd, &addr, length);
?
In mathematics, an argument of a function is a value provided to obtain the function's result. It is also called an independent variable. For example, the binary function has two arguments, and , in an ordered pair . The hypergeometric function is an example of a four-argument function.
When an argument is passed by value, the C function receives a copy of the actual value of the argument. To specify that the argument should always be passed by value, use the keyword ByVal preceding the parameter declaration for that argument in the Declare statement for the C function.
An argument is a way for you to provide more information to a function. The function can then use that information as it runs, like a variable. Said differently, when you create a function, you can pass in data in the form of an argument, also called a parameter.
Arguments are specified after the function name, inside the parentheses.
It should be called like this:
bind (sd, (struct sockaddr *) &addr, length);
As for why, this is the C way of doing polymorphism, if you look at the definitions of those structures:
struct sockaddr {
unsigned short sa_family; // address family, AF_xxx
char sa_data[14]; // 14 bytes of protocol address
};
// IPv4 AF_INET sockets:
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
};
// IPv6 AF_INET6 sockets:
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
};
They all share the same first member, sa_family
when you pass a pointer to one of those structures to bind()
you first cast it to struct sockaddr *
and inside the function, sa_family
is used to determine which structure you passed and cast back to the right one, instead of having one function for each structure you have one function that accepts sockaddr*
.
Another way to look at it, from an OOP perspective, imagine that sockaddr
is the base class for sockaddr_in
and sockaddr_in6
, and passing a pointer to sockaddr
is similar to casting to the base type and calling a generic function. hope this makes it more clear.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With