TCP Client - Basic Socket Programming Tutorial In C

Posted by Coding Yoda on November 14th, 2018

In this video/blog post I run through creating a TCP Server using C sockets, it's a follow up post to the TCP client. Sockets are a way of connecting two nodes on a network so that they can communicate with each other. The client socket reaches out to the server and the client receives back a response. In this video I run through setting up the client to send a message to the Server. In the next video I'll go over setting up the Sever to receive the message.

Steps for setting up the TCP client

  • Create TCP Client socket - Socket()
  • Create the server Address
  • Connect the created client socket to server. - Connect() and Write()
  • Receive the response from the server and print to the screen - Read()
  • Close the connection - Close()

Sockets

The address of a socket in C is a character string which is basically an entry in the file system.
The address of a socket in the Internet domain is the IP address of the server. In the exmaple we are just connecting to our own machine so we use INADD_ANY which means it's not a specific IP.
Sockets also need a port number of the host. The internet port for a http server is 80, 21 for FTP I picked 8001 of the example.
In the video I use stream sockets, stream sockets offer communications as a continuous stream of characters. The other type is datagram sockets, with datagram sockets you have to read entire messages at once.

socket programming diagram

Thanks for reading/watching and I hope this helps.

You can read/watch now to create the TCP Server here