in c socket programming, how can I send and received on the same port?
Use the FIFO or PIPE
You can't use the same port for send and receive.
If you use a single PIPE for read and write then u can use the same port for send and receive.
Really? If that were so, then how can a webserver first receive and then send on the same port (usually TCP 80)? Same goes for mail servers, FTP, SSH, and any other kind of 2-way communication on the net.
what I'm sure of is that I can receive multiple connections on the same port as long as the peer's IP and port no are different per connection, not sure for using the same port for read and receive, will select() solve the problem?
Fine pludi , tell me whether more than one process can occupy a same port while they established in a same ip !
Yes. Have your program open a socket in listening mode, and have it fork() on accept(). The child inherits the new socket, and can transfer (read and write) data through it. Meanwhile the parent can still accept new connections on the same port, and spawn additional child processes. All the while they use the same TCP or UDP port. That's the same mechanism that Apache uses if you've configured it in prefork mode.
To illustrate:
# netstat -antp | grep ':80'
tcp 0 0 1.2.3.4:80 0.0.0.0:* LISTEN 534/httpd2-prefork
tcp 0 0 1.2.3.5:80 0.0.0.0:* LISTEN 534/httpd2-prefork
From a different machine:
$ telnet 1.2.3.4 80
Trying 1.2.3.4...
Connected to 1.2.3.4
Escape character is '^]'.
HEAD / HTTP/1.1
Host: 1.2.3.4
Connection: keep-alive
Accept: */*
HTTP/1.1 403 Forbidden
Date: Thu, 11 Mar 2010 07:44:44 GMT
Server: Apache/2.2.3 (Linux/SUSE)
Vary: accept-language,accept-charset
Accept-Ranges: bytes
Connection: close
Content-Type: text/html; charset=iso-8859-1
Content-Language: en
The keep-alive directive will keep the connection open. Meanwhile, we take another look at netstat:
# netstat -antp | grep ':80'
tcp 0 0 1.2.3.4:80 0.0.0.0:* LISTEN 534/httpd2-prefork
tcp 0 0 1.2.3.5:80 0.0.0.0:* LISTEN 534/httpd2-prefork
tcp 0 0 1.2.3.4:80 1.2.9.8:59388 ESTABLISHED 1033/httpd2-prefork
OMG, 2 processes on the same Port, one listening the other communicating. But wait, it gets even worse if we open 2 telnet sessions:
# netstat -antp | grep ':80'
tcp 0 0 1.2.3.4:80 0.0.0.0:* LISTEN 534/httpd2-prefork
tcp 0 0 1.2.3.5:80 0.0.0.0:* LISTEN 534/httpd2-prefork
tcp 0 0 1.2.3.4:80 1.2.9.8:39364 ESTABLISHED 22914/httpd2-prefor
tcp 0 0 1.2.3.4:80 1.2.9.8:39365 ESTABLISHED 26486/httpd2-prefor
Now it's even 3 processes on the same port.
You see, it is possible, as long as you have a central instance (in this case the main Apache process) handling incoming requests and delegating them to other processes.