Socket Programming — Linux
2 min readAug 14, 2016
What is a Socket?
Socket is a virtual endpoint of any kind of network communication done between two hosts over in a network. Sockets can be used in many languages like Java, C++, C etc. The socket API on Linux is similar to BSD/UNIX sockets from which it has evolved. Although over time the API has become slightly different at few places and now the newer official standard is POSIX sockets API which is same as BSD sockets.
How to create a socket?
To create a socket we can use the Socket function. Here is the sample code.
socket() creates a socket and returns a descriptor which can be used in other functions. The above code will create a socket with following properties.
- Address Family : AF_INET (IP Version 4)
- Type : SOCK_STREAM (TCP Protocol)
- Protocol : 0 (Default IP Protocol)
- Instead of using SOCK_STREAM type of sockets there is another type called SOCK_DGRAM which indicates the UDP protocol.
Connect Socket to a Server.
- We need the IP address & the Port number to our above created socket. Then we can connect to a remote server on a given port number.
- To connect to a remote server we need to do a couple of things. First is to create a sockaddr_in structure with proper values.
- The sockaddr_in has a member called sin_addr of type in_addr which has a s_addr which is nothing but a long. Function inet_addr is a very handy function to convert an IP address to a long format.
#server.sin_addr.s_addr = inet_addr(“127.0.0.1”); - Using the Connect() needs a socket and a sockaddr structure to connect.
- Try connecting to a port different from port 80 and you should not be able to connect which indicates that the port is not open for connection.