This page was last modified 2010-04-23 10:51:32 by Puchu.Net user Choco. Based on work by Puchu.Net user(s) Omoikane. (Show history)
This article will be divided into two parts. Part 1 (you are reading it) will be a quick look at various related system calls. While these functions are for Linux and UNIX platforms, the same functions exist under Windows, and have similarly named methods for other platforms.
Information related to client/server interaction, Winsock2, DNS, and references used in these articles is in Sockets (Part 2).
Different processor architecture and network protocol operate with different byte ordering (endianness, for example x86 is little-endian, TCP/IP is big-endian), so to bridge the different ends of a connection macros are used to shift bytes to network byte order:
Or, when converting from network byte order:
Create a new socket. If value
Socket programming always involve the socket descriptor in some ways, and socket abstracts the session for application. This is how your application will keep track of different connections.
bind / listen / accept
This function binds your socket to a local IP address, something you want to do if you are the server that will be listening on an address and a port.
Once your server is bound to an address, it should be listening for a connection.
Here the parameter n determines now many requests will be queued before the server starts to refuse them. The number varies depending on your platform and your application.
Once you have determined that there are some connection requests queued up, you can remove those requests by accepting them.
By calling the function to accept a request, if there is a connection request queued the function will fill in the client address information so that we can transfer data to/from the client.
An example of the function calls for a server would be:
If you need to handle multiple connections, your code needs to store and maintain the associated socket descriptor and address information.
This function will connect you to the server specified in the socket address information.
This is required for connection-based protocol like TCP, but optional for UDP.
send / sendto
These functions will return the number of bytes actually sent, and it may not match the amount you specified. Therefore it is the responsibility of the application to check for this situation and send the remaining data.
recv / recvfrom
These functions will read data into buf from the network.
This function will shut down all or part of the connection as specified by fd. The parameter how is used to determine:
This will close the socket descriptor, and your connection. It is possible for close to fail due to final I/O not finishing. In addition, because the kernel will buffer read/write operations, it may take a brief delay after calling
To Be Continued...
In part 2 of this article we will study socket programming using system calls described here.