Simple Socket Questions
I'm learning socket programming on Linux. I have some questions what I would like to ask. I hope you will help me! ;)
That's why, that I'm new to Network Programming, I like to keep things simple.
When I use connect();, I need to connect like this:
Why can't I use connect like this?
connect(fd, (struct sockaddr *)&server, sizeof(struct sockaddr));
Why can't I just type IP address there, instead of (struct sockaddr *)&server. And what is that sizeof(struct sockaddr) thing? Why do I need it? Now for the server part. When making server, I need to declare this:
connect(fd, "126.96.36.199", sizeof(struct sockaddr));
And do this:
And in the end, after socket(); bind(); listen(); I need to accept(); Why does accept need this sin_size as an argument? Is it posible to make Networking app's, without using structures(sockaddr_in or others)?
Thank you! :p
>>struct sockaddr *)&server
This is a pointer to a structure that is recognised and used by the connect() function. You can't just put in a string constant, like "127.0.01", it ain't going to work.
sizeof gets you the size of the structure sockaddr in bytes.
You need it because connect needs to know it.
Similar answer to the accept() question you've asked, those functions need to know the size of the structure you're passing to them.
If you want to see sample implementations of these functions, google your way to beej's networking programming pages.
a) A struct sockaddr contains more than just an IP address.
It contains information about the destination address (which might
not even be an IP address!), the port, and some other things.
Note that it's a (struct sockaddr) not a (struct sockaddr_in).
The former is a socket address (generic) the second is an
internet protocol socket address.
b) accept is going to fill in the number of bytes that the kernel
dropped into the cliaddr pointer you passed as the second argument
to it. When you call accept() it uses *addrlen to figure out how big
the cliaddr is, and when it returns, it fills in the number of bytes stored.
but why addrlen has to be a pointer?