Mr.Y
Mr.Y

Reputation: 131

Functionality to catch arriving connection on tcp port

I have an application running on TCP port 4000 and I want to perform some verification on the IPs which are connecting with port 4000. So, I already have the verification API which is basically a post API. I am looking forward to calling this API whenever any new client IP connects with port 4000. Is this possible in Linux in any language?

Upvotes: 0

Views: 271

Answers (2)

user2311560
user2311560

Reputation: 104

You can use tcpdump to listening for a new connection on 4000 port and take action on each stdout line from tcpdump and using sed to extract address IP. Then you can use for example xargs to make action.

To filter for tcpdump you can use

tcpdump -n 'tcp[tcpflags] & tcp-syn != 0 and port 4000 and inbound'

Upvotes: 1

Liam Kelly
Liam Kelly

Reputation: 3704

If I am understanding your question correctly, you need the client's IP Address that is connecting to your server on port 4000. You then want to send that IP to your API via an HTTP POST and depending on the result you will accept or drop the client.

It seems like the only thing you are really missing is the getpeername syscall. No matter the language you are using, when you accept or create a TCP connection a socket is created in the OS and data is sent to and from it and your application. Once this socket is created you can query the OS to tell you what is the remote IP address/TCP port in the connection via the getpeername syscall. In 'C' there is a function that does this for you called getpeername. If you are using another language you may have another function or the data could already be gathered and placed in a data structure at conenction time (in Go you can just call Conn.RemoteAddr()).

Knowing this you can do the following:

  • Accept the client connection, but do not read/write any data
  • Grab the client's IP Address from the getpeername syscall
  • Send the IP Address to your API via a POST
  • Read and Write data to the client if API returns authorized responce, else drop the connection

Upvotes: 1

Related Questions