Establishing A TCP Socket Connection Using Specific Client IP And Port For Enhanced Security

Introduction

 
This article demonstrates a way how to establish a socket connection using a specific client ip:port. Creating a socket connection between client and server is a standard step for TCP communication. As a standard step, when a socket connection is created to establish a TCP connection from a client to server, the actual (or a default) IP address of the client is used by default. Usually, the client has this default IP address assigned to it by the Local area network which the client is connected with. Moreover, a default port number is used from a valid port numbers range, and these default ip:port is bound with the client socket. This client socket then establishes a TCP socket connection with the TCP server. A specific server IP and port number must have to be defined to establish such a socket connection.
 

Motivation

 
It is possible that we need to bind the client socket with a specific client IP and port number, instead of the default IP address and port number. Binding the client socket with a specific IP address and port number may be required for enhanced security and also allows the application to be configurable to use any given IP address. Binding with a specific IP address may also be required in the case when there are more than one client IP addresses available. If the client computer/device has more than one network available/up simultaneously such as a Virtual network or WIFI network or Cellular (Mobile broadband) network, besides Ethernet Local area network then each network will make its corresponding IPv4 address available. These different kinds of network adapters are sometimes available at the client device and the device may switch its network connection between multiple network adapters. However, the application running on that device may need to use a specific IP address of a specific network while a client socket is created. This is how the client device can be forced to use a specific network by virtue of binding the client socket with the IP address of that specific network.
 

Procedure

 
The source code given in this section is written in .NET C#. We define a specific client IP address and port number at first (the application can also have the flexibility to retrieve the specific client IP and port from a configuration file). Then the client application finds all available client IP addresses at the client machine and then selects the one which is the defined/given IP address. The specific client IP address will be represented by 'client_specific_ip_address' and the port will be represented by ' client_specific_port_no ' in the code segment attached.