netstat process name information programmatically or from procfs - c

I have a requirement to get all the port numbers that a particular program is listening on. The program itself is a generic server type program (lets call it myserverd). myserverd can be configured to listen on any TCP port, and there can be more than one instance of myserverd running on a machine.
I can get the ports being used by running instances of myserverd by grep'ing for myserverd in netstat -natp (p option to display the program name in netstat)
I am trying to see this information in procfs (/proc/net/tcp) but it doesn't show any process names... my question is: is there a good/reliable API that can be used to programmatically figure out what processes are listening to a particular port (or get all process names bound to all listening ports)... ?

You can find the source code for netstat here: https://github.com/mirror/busybox/blob/master/networking/netstat.c. If you look through it, you should see how netstat gets the pids/names of bound processes.
Specifically, look at the prg_cache_load() function, as netstat just polls /proc/net/tcp anyway.

Related

Short and simple way to send a syslog message to a remote machine?

I have a C program that is currently logging events via syslog, after calling openlog to specify a program name.
The meat of my program that logs events to syslog is just three lines:
openlog(program_name, 0, facility);
syslog(log_level|facility,"%s\n",message);
closelog()
However, there are situations in my program where I should be sending the syslog event to a remote machine instead of logging locally, as the syslog function ordinarily does. What I'd like to do is optionally supply some other information to the function containing the above lines, such as a host (and optionally, a port), and whether to use udp or tcp, and if such information is present, send the syslog event to another machine via the rsyslog protocol to that machine.
What I categorically do NOT want to do is have to change any of the configuration files for the syslog daemon. I simply wish to, under program control, be able to send the same messages to another machine's syslog that would have otherwise shown up locally using the above three lines.
The only way I've been able to verify for sure I would be able to do this under program control is to construct a message manually that conforms to RFC 5424, and send it over a socket connection manually. Will I have to write the code to do all of this from scratch myself, or is there some existing facility out there (open source) that will do what I need?
Not in C but I used this to test my syslog server...
echo "$(TZ=UTC date +%FT%T.%NZ) $(uname -n) subsystem: hello" | socat -d -d - udp-sendto:syslog-server:514

Checking port availability in Linux

I need to launch several instances of a game in the same computer using Linux. The game is created launching a server at a specified port number (using a command line command with --port NUMBER as an argument) and then each of the players attachs itself to that port to play the game (in a similar fashion).
I need to launch hundreds of games in parallel through a little C program that uses the stdlib.h system library function (system(const char *command)) to launch the game server and the game players.
What I need to know is: how can I check from withing that C program that a port is available before launching the game server on that port number? It´s important to note that my program itself does not bind to any port, it just launchs (with system) the program that will actually try to connect to that port.
You have to use bind() directly, and if it doesn't succeed you can try another port.
Checking if a port is free and then binding is not possible and would be a race condition: You just checked, that a port was free, but someone already used it.
Reading /proc/net/tcp can help you though, but the race condition still applies.
The simplest way is normally trying to open a port and then handle the error as a already used port. A nice example can be found here
Three simple steps:
Try to open socket on the port you desire
If it works return true and close the socket
If not, return false
In the example given, they do it remotely, but you easily can change that.

Bind failed: Address already in use

I am attempting to bind a socket to a port below:
if( bind(socket_desc,(struct sockaddr *) &server, sizeof(server)) < 0)
{
perror("bind failed. Error");
return 1;
}
puts("bind done");
But it gives:
$ ./serve
Socket created
bind failed. Error: Address already in use
Why does this error occur?
Everyone is correct. However, if you're also busy testing your code your own application might still "own" the socket if it starts and stops relatively quickly. Try SO_REUSEADDR as a socket option:
What exactly does SO_REUSEADDR do?
This socket option tells the kernel that even if this port is busy (in
the TIME_WAIT state), go ahead and reuse it anyway. If it is busy,
but with another state, you will still get an address already in use
error. It is useful if your server has been shut down, and then
restarted right away while sockets are still active on its port. You
should be aware that if any unexpected data comes in, it may confuse
your server, but while this is possible, it is not likely.
It has been pointed out that "A socket is a 5 tuple (proto, local
addr, local port, remote addr, remote port). SO_REUSEADDR just says
that you can reuse local addresses. The 5 tuple still must be
unique!" by Michael Hunter (mphunter#qnx.com). This is true, and this
is why it is very unlikely that unexpected data will ever be seen by
your server. The danger is that such a 5 tuple is still floating
around on the net, and while it is bouncing around, a new connection
from the same client, on the same system, happens to get the same
remote port. This is explained by Richard Stevens in ``2.7 Please
explain the TIME_WAIT state.''.
You have a process that is already using that port. netstat -tulpn will enable one to find the process ID of that is using a particular port.
Address already in use means that the port you are trying to allocate for your current execution is already occupied/allocated to some other process.
If you are a developer and if you are working on an application which require lots of testing, you might have an instance of your same application running in background (may be you forgot to stop it properly)
So if you encounter this error, just see which application/process is using the port.
In linux try using netstat -tulpn. This command will list down a process list with all running processes.
Check if an application is using your port. If that application or process is another important one then you might want to use another port which is not used by any process/application.
Anyway you can stop the process which uses your port and let your application take it.
If you are in linux environment try,
Use netstat -tulpn to display the processes
kill <pid> This will terminate the process
If you are using windows,
Use netstat -a -o -n to check for the port usages
Use taskkill /F /PID <pid> to kill that process
The error usually means that the port you are trying to open is being already used by another application. Try using netstat to see which ports are open and then use an available port.
Also check if you are binding to the right ip address (I am assuming it would be localhost)
if address is already in use can you just want to kill whoso ever process is using the port, you can use
lsof -ti:PortNumberGoesHere | xargs kill -9
source and inspiration this.
PS: Could not use netstat because it not installed already.
As mentioned above the port is in use already.
This could be due to several reasons
some other application is already using it.
The port is in close_wait state when your program is waiting for the other end to close the program.refer (https://unix.stackexchange.com/questions/10106/orphaned-connections-in-close-wait-state).
The program might be in time_wait state. you can wait or use socket option SO_REUSEADDR as mentioned in another post.
Do netstat -a | grep <portno> to check the port state.
It also happens when you have not give enough permissions(read and write) to your sock file!
Just add expected permission to your sock contained folder and your sock file:
chmod ug+rw /path/to/your/
chmod ug+rw /path/to/your/file.sock
Then have fun!
I was also facing that problem, but I resolved it.
Make sure that both the programs for client-side and server-side are on different projects in your IDE, in my case NetBeans. Then assuming you're using localhost, I recommend you to implement both the programs as two different projects.
To terminate all node processes:
killall -9 node
First of check which port are listening,
netstat -tlpn
then select available port to conect,
sudo netstat -tlpn | grep ':port'
Fix it into also to your server and clients interfaces. Go Barrier tab -> change settings, -> port value type -> save/ok
Check both clients and server have similar port values
Then Reload.
Now it should be ok.
Check for running process pid:
pidof <process-name>
Kill processes:
sudo kill -9 process_id_1 process_id_2 process_id_3

How to find out data being buffered between two clients connected using unix domain socket on Linux

I have a producer and a client connecting using Unix Domain Sockets. The netstat -nap command shows amount of data getting buffered between two processes for TCP/IP socket but not for Unix domain socket
How to find out send buffer and receiver buffer sizes for Unix Domain Socket from outside of the code?
netstat does not have POSIX compliance. That means you may not get identical information running netstat on different OSes. tcp/ip buffer settings are normally a default system setting.
You have to login on both boxes to run netstat to get tcp internals information, for the sockets. I'm sure you know that already, but I"m trying to be clear. tcp system information is in wildly different locations from Linux to another OS, say Solaris.
What is the output of uname -a on the UNIX box?

Address already in use while executing C socket programme

Hii All,
While running a socket programme (server side ) am getting message like
Address already in use
Am trying to connect to port 80 since port 80 is reserved for https application So before running server side programme i am closing all application that uses https application ,is it enough...
or am doing it wrong??
Am trying to make a communication between browser and termial...
You must run your application as super user(root) on Linux or administrator privileges on Windows in order to bind to port 80. This is the case for all service ports, which is < 1024. Either that or there still is another program binded to that port.
Try using netstat to find out what programs might be listening on port 80.
Example:
on Linux:
netstat -punta
on Windows:
netstat -ban
Both must be run with super user/admin privileges in order to see the program names that bind to specific ports.
If you just closed another process listening on 80 port, this port will be blocked for a certain timespan depending on your OS. This behavior is here to prevent an attacker to crash a service on your machine and immediately restart a malicious service on the same port.
This behavior can be disabled by using SO_REUSEADDR (by using setsockopt).
If your main problem is to communicate from a custom server to your broswer, you can use any port in your server for providing HTTP (8080 is common for that), just specify the port in the url http://server:port/ (ie. http://localhost:8080/)

Resources