I have started implementing a server-client model with UNIX domain sockets of SOCK_STREAM type.
Thanks in advance
You need to avoid connecting again if your socket is already connected, you can keep some flag in your client code that indicates your client socket is already connected or not, based on that skip connecting again.
I have edited your server code below to show what I am trying to say in comments(You need to put accepted fd in select read set too, so that you can check any of clients posted any data, also you have multiple clients connected to you so you will have to keep accepted sockets in an array):
int cltfdlen = 0;
int cltfds[FD_SETSIZE];
int maxFD = sockfd;
int sun_path_size = sizeof(client_address.sun_path);
client_address.sun_family = AF_UNIX;
strncpy(client_address.sun_path, SOCKET_NAME, sun_path_size);
client_len = sizeof(client_address);
cli_interval.tv_sec = 60;
cli_interval.tv_usec = 0;
while (1) {
FD_ZERO(&read_fds);
FD_SET(sockfd, &read_fds);
for(i=0;i<cltfdlen;cltfdlen++)
FD_SET(cltfds[i], &read_fds);
int activity = select(maxFD + 1, &read_fds, NULL, NULL, &cli_interval);
if ((activity < 0) && (errno !=EINTR)) {
printf("socket select failed errno %d\n", errno);
return 1;
}
if (FD_ISSET(sockfd, &read_fds)) {
cli_sockfd = accept(sockfd,
(struct sockaddr *)&client_address,
&client_len);
if(cli_sockfd < 0) {
printf("accept from IPC socket failed");
return 1;
}
else
{
cltfds[cltfdlen++] = cli_sockfd;
if(maxFD < cli_sockfd)
maxFD = cli_sockfd
continue;
}
}
msg = (msg_t *) malloc(sizeof(msg_t));
if (msg == NULL) {
printf("Memory allocation failed for msg");
close(ipc_sockfd);
ipc_sockfd = -1;
return 1;
}
memset(msg, 0, sizeof(msg));
for(i=0;i<cltfdlen;i++)
{
if(FD_ISSET(cltfds[i], &read_fds))
{
if (read(cltfds[i], (void *)msg, sizeof(msg_t)) == -1) {
printf("Read from IPC socket failed");
return 1;
}
}
}
close(cli_sockfd);
cli_sockfd = -1;
}
Related
I have a tcp server and I want to make it so after it accepts the first client it doesn't wait on the accept function and just goes on if no-one else has connected
while (1)
{
SOCKET ClientSocket = accept(Socket, (sockaddr *)&Client, &ClientSize);
if(ClientSocket == INVALID_SOCKET)
{
Error("accept failed.\n");
}
ClientSockets[ClientSocketsIndex++] = ClientSocket;
Result = connect(ClientSocket, (sockaddr*)&Client, ClientSize);
sockaddr_in From;
int FromSize = sizeof(From);
Result = recv(ClientSocket, Message, sizeof(Message), 0);
if (Result == SOCKET_ERROR)
{
Error("recv failed.\n");
}
Result2 = getpeername(ClientSocket, (sockaddr*)&From, &FromSize);
if (Result2 == SOCKET_ERROR)
{
Error("getpeername failed.\n");
}
Here I take the ClientSocket with accept() and add it to an array where I store all ClientSockets and then receive a buffer. The problem is that after each loop it waits for a new ClientSocket.
The Error() function is just a one I made for printing to the console and quitting if I encounter an Error btw.
First off, calling connect() on the SOCKET returned by accept() is wrong. Get rid of that.
Second, if you want your loop to service multiple clients properly, then use select() (or equivalent). Don't call accept() until select() tells you that a new client is waiting to be accepted. Likewise, don't call recv() until select() tells you that a client in your array is waiting to be read from.
Try something more like this:
const size_t MAX_SOCKETS = ...;
SOCKET ClientSockets[MAX_SOCKETS];
size_t NumClientSockets = 0;
...
while (true)
{
fd_set readfds;
FD_ZERO(&readfds);
FD_SET(Socket, &readfds);
for(int i = 0; i < NumClientSockets; ++i)
{
FD_SET(ClientSockets[i], &readfds);
}
if (select(0, &readfds, NULL, NULL, NULL) > 0)
{
if (FD_ISSET(Socket, &readfds))
{
ClientSize = sizeof(Client);
SOCKET ClientSocket = accept(Socket, (sockaddr *)&Client, &ClientSize);
if (ClientSocket == INVALID_SOCKET)
{
Error("accept failed.\n");
}
else if (NumClientSockets == MAX_SOCKETS)
{
closesocket(ClientSocket);
}
else
{
ClientSockets[NumClientSockets] = ClientSocket;
++NumClientSockets;
}
}
size_t i = 0;
while (i < NumClientSockets)
{
if (!FD_ISSET(ClientSockets[i], &readfds))
{
++i;
continue;
}
Result = recv(ClientSockets[i], Message, sizeof(Message), 0);
if (Result <= 0)
{
if (Result == SOCKET_ERROR)
Error("recv failed.\n");
for(size_t j = i + 1; j < NumClientSockets; ++j)
{
ClientSockets[j - 1] = ClientSockets[j];
}
--NumClientSockets;
continue;
}
// use Message up to Result bytes as needed...
++i;
}
}
}
I have a system where two machines are connected, and send/receive information to each other. One of the servers sends RTP voice packets using RTSP protocol to the other one. I should implement an edge case, and it requires the following;
When the server goes down/crashes, socket connection is lost. I should create and connect a new socket when the server is available. In this regard, I remove the existing socket, create a new one ( with a new file descriptor ). But it does not connect to the server even if it is available..
static int socket_new_try_connect( struct rtsp_session *s )
{
int flags;
int res = -1;
socklen_t slen;
struct hostent *he;
struct ast_hostent h;
while( res < 0 )
{
sleep(2);
if ((he=ast_gethostbyname("10.1.1.6", &h)) == NULL) {
log("socket_new_try_connect::ast_gethostbyname ERROR !\n");
continue;
}
memset(&s->sin, 0, sizeof(s->sin));
s->sin.sin_family = AF_INET;
s->sin.sin_port = htons(8554);
memmove(&s->sin.sin_addr, he->h_addr, sizeof(s->sin.sin_addr));
/* socket */
s->sock = socket(AF_INET, SOCK_STREAM, 0);
if (s->sock < 0) {
log("socket_new_try_connect::Unable to create RTSP session socket\n");
continue;
}
log("socket_new_try_connect::new RTSP socket is created. \n");
struct timeval timeout;
timeout.tv_sec = 5;
timeout.tv_usec = 0;
/*if(setsockopt(s->sock, SOL_SOCKET, SO_REUSEADDR, (char *)&timeout, sizeof(timeout)) < 0){
perror("setsockopt() SO_REUSEADDR");
close(s->sock);
continue;
}*/
if(setsockopt(s->sock, SOL_SOCKET, SO_RCVTIMEO, (char *)&timeout, sizeof(timeout)) < 0){
log(LOG_ERROR, "setsockopt, EXIT FAILURE!\n");
perror("setsockopt()");
close(s);
continue;
}
if(setsockopt(s->sock, SOL_SOCKET, SO_SNDTIMEO, (char *)&timeout, sizeof(timeout)) < 0){
perror("setsockopt()");
close(s);
continue;
}
flags = fcntl(s->sock, F_GETFL);
fcntl(s->sock, F_SETFL, flags | O_NONBLOCK);
while(1)
{
res = connect(s->sock, (struct sockaddr *)&s->sin, sizeof(s->sin));
log(LOG_NOTICE, "socket_new_try_connect::connect RESULT : %d \n",res);
if(res < 0 && errno != EINPROGRESS) {
sleep(1);
continue;
}
else if( res < 0 )
{
log("socket_new_try_connect::Cannot connect to RTSP recording server. Error :%s\n", strerror(errno));
close(s->sock);
break;
}
else
{
log("socket_new:: SOCKET CONNECT IS SUCCESSFULL ! RESULT : %d \n",res);
return 1;
}
}
}
return 1;
}
With the code above, I am getting "Operation in progress" error. I also saved the messages when the server is available again after getting crashed;
tcp messages
Could you please help me to elaborate the problem ?
I have a program where i want to forward packet coming from one interface ( VxBridge) & sending it on another interface (ens3:- listing raw sockets ) and vice versa also.
Although my program listens to 3 interfaces
1. VxBridge --> Listing on port 1702
2. ens3 --> listen raw interface
3. tap interface --> tun tap interface
Packet coming from ens3 <--> VxBridge
Problem :-
So program works fine if i have running Wireshark listing on ens3.
If wireshark is stop then Program doesn't listen to packets on ens3. Below is code snippet of program.
Also i believe it is related to somewhat in select() function where waiting of I/O event to occur.
I know i am doing something really wrong here. Any help in redirection would be appreciated.
Below is program :-
main(int argc, char **argv)
{
struct sockaddr_in addr;
struct sockaddr_ll daddr;
fd_set rfds;
fd_set hfds;
int cc,ccd;
struct sockaddr_in from;
size_t fromlen;
int fdmax;
int i;
char* newframe=NULL;
int fdcounter =0;
char *vb = NULL;
int vxSocketfdSet,hwSocketfdSet,tapSocketfdSet;
vxSocketfdSet= hwSocketfdSet=tapSocketfdSet=0;
// Open sockets for L2 device
if (send_to_hw){
if ( ( destsock_fd = socket( PF_PACKET , SOCK_RAW , IPPROTO_RAW) ) < 0){
perror("destsocket creation failed exit");
exit(1);
}
global_fd[fdcounter]=destsock_fd;
fdcounter++;
}
memset(&daddr, 0, sizeof(struct sockaddr_ll));
daddr.sll_family = AF_PACKET;
daddr.sll_protocol = htons(ETH_P_ALL);
daddr.sll_ifindex = if_nametoindex("ens3");
if (bind(destsock_fd, (struct sockaddr*) &daddr, sizeof(daddr)) < 0) {
printf(" ens3 bind failed\n");
close(destsock_fd);
}
struct ifreq ifr;
memset(&ifr, 0, sizeof(ifr));
snprintf(ifr.ifr_name, sizeof(ifr.ifr_name), "ens3");
if (setsockopt(destsock_fd, SOL_SOCKET, SO_BINDTODEVICE, (void *)&ifr, sizeof(ifr)) < 0) {
printf("setsockopt to ens3 failed");
}
/* Open a socket for receiving frames from the Bridge, and forwarding to other l2fwd instances of remote host. */
if ((sock_fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
perror("socket");
exit(1);
}
global_fd[fdcounter]=sock_fd;
if (vb != NULL)
{
/* create a TAP interface and attach to virtual bridge */
if ((tap_fd = tap_alloc_via_tun_helper(argv[tap_ip_arg], vb)) < 0) {
exit(1);
}
global_fd[fdcounter]=tap_fd;
fdcounter++;
}
memset(&addr, '\0', sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = INADDR_ANY;
addr.sin_port = htons(DE);
if (bind(sock_fd, (void *) &addr, sizeof(addr)) < 0) {
perror("bind");
exit(1);
}
write(1, "> ", 2);
if (pcap)
tv_wait = &pcap_flush_delay;
for (;;) {
FD_ZERO(&rfds);
fdmax = 0;
for ( i =0;i<=fdcounter;i++){
FD_SET(global_fd[i], &rfds);
if (global_fd[i] > fdmax)
fdmax = global_fd[i];
}
if (select(fdmax + 1, &rfds, 0, 0, tv_wait) < 0) {
perror("select");
continue;
}
for (i = 0;i <= fdcounter; i++)
{
if (FD_ISSET(global_fd[i], &rfds)) {
printf ("\nfdset value is %d &&& %d\n",i,global_fd[i]);
if (i==0)
{
printf("hw set ");
hwSocketfdSet = 1;
destsock_fd=global_fd[i];
}
else if (i==1){
printf ("vx Set x");
vxSocketfdSet = 1;
sock_fd=global_fd[i];
}
else if (i ==2){
tapSocketfdSet = 1;
tap_fd=global_fd[i];
}
break;
}
}
if (vxSocketfdSet){
fromlen = sizeof(from);
cc = recvfrom(sock_fd, buf, sizeof(buf), 0, (void *) &from, &fromlen);
if (cc < 0) {
perror("recvfrom");
continue;
}
printf("\nvx frame buf\n");
tempFrom = &from;
forward(buf, cc, &from,0);
}
if (tapSocketfdSet){
printf("tap frame received");
/* Ethernet frame received from local XC. */
if ((cc = read(tap_fd, buf, sizeof(buf))) < 0) {
perror("read");
continue;
}
forward(buf, cc, NULL,0);
}
if (hwSocketfdSet){
printf ("Packet received on ens3 header buffer\n");
if ((ccd = read(destsock_fd, hbuf, sizeof(hbuf))) < 0) {
printf ("error reading");
perror("read");
continue;
}
if (headerbuff != NULL && tempFrom != NULL)
{
printf("headerbuff =%u\n",headerbuff);
printf("headerbuff+ACTUAL_PAYLOAD_OFFSET %u\n",headerbuff+ACTUAL_PAYLOAD_OFFSET);
memcpy(headerbuff+ACTUAL_PAYLOAD_OFFSET,hbuf,ccd+ACTUAL_PAYLOAD_OFFSET);
newframe=headerbuff;
// printing packet with raw buffer
// weird logic is used don't try to understand this one.
// forward(headerbuff, ccd+ACTUAL_PAYLOAD_OFFSET,tempFrom,1);
}
}
vxSocketfdSet=hwSocketfdSet=tapSocketfdSet=0;
}
}
Enabling promiscuous mode on the interface allows it to receive packets for any address. Otherwise the interface ignores packets for foreign addresses. To do this, set the IFF_PROMISC bit in the flags argument to the SIOCSIFFLAGS ioctl call.
Don't forget to turn it off when the program ends.
Here is my server code, dont know how i got
failed to select : Invalid argument
its work fine on my mac, but not on linux.
can someone tell me where i did wrong ?
Im just new begynniner in c programming.
server.c
int server(int port){
int request_sd, newfd;
socklen_t clientaddrlen;
fd_set masterList;
fd_set readFd;
int bind_adress = 0, listen_connect = 0;
int fd_max;
int select_client, i;
struct sockaddr_in server_adr;
struct sockaddr_in client_adr;
if (!getcwd(root_path, PATH_LEN))
{
perror("set path");
}
request_sd = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
if (request_sd < 0)
{
perror("failed: ");
return -1;
}else printf("create new socket i complete: %d\n", request_sd);
memset(&server_adr, 0 , sizeof (struct sockaddr_in));
server_adr.sin_family = AF_INET;
server_adr.sin_addr.s_addr = INADDR_ANY;
server_adr.sin_port = htons(port);
int activate = 1;
if (setsockopt(request_sd, SOL_SOCKET, SO_REUSEADDR, &activate, sizeof(int)) == -1)
{
perror("setsockopt: ");
return -1;
}
bind_adress = bind(request_sd, (struct sockaddr*) &server_adr, sizeof(struct sockaddr_in));
if (bind_adress < 0 )
{
perror("failed to bind : ");
return -1;
}
listen_connect = listen(request_sd, 10);
if (listen_connect <0)
{
perror("failed to listen : ");
return -1;
}
printf("\nListening for connections on port: %d\n\n", port);
fflush(stdout);
FD_ZERO(&masterList);
FD_ZERO(&readFd);
FD_SET(request_sd, &masterList);
fd_max = request_sd;
while(1){
readFd = masterList;
if((select_client = select(fd_max+1, &readFd, NULL, NULL, NULL)) < 0){
perror("FAILED TO SELECT");
}
for ( i = 0; i <= fd_max; i++)
{
if(FD_ISSET(i,&readFd))
{
if(i == request_sd)
{
newfd = accept(request_sd, (struct sockaddr*) &client_adr,
(socklen_t *) &clientaddrlen);
if (newfd == -1 )
{
perror("failed to accept :");
return -1;
}
FD_SET(newfd, &masterList);
if (newfd > fd_max)
{
fd_max = newfd;
}
Since select() is complaining about a bad parameter, and you are passing only two parameters to it, that means either fd_max is invalid or readFd is invalid. The documentation states:
EINVAL
nfds is negative or the value contained within timeout is invalid.
Since you are not using the timeout parameter, look at your fd_max variable, make sure you are not overflowing it.
Aside from that, you should use fd_copy() instead of readFd = masterList on platforms that support it.
FD_COPY(&masterList, &readFd);
A better option is to use poll() or epoll() instead of select(). It is easier to manage, and it tells you the exact socket(s) that satisfied the wait so you don't have to hunt for them.
The following code is a test program wriiten to understand the behaviour of select() call in a TCP client program.
What I observe is that the select is not blocking, instead the program is blocking on recv().
The output is as follows:
Wait on select.
Wait on recv.
...
My question is why the select() returns a success? Ideally it should be blocking on the select() instead of recv().
The TCP server is sending a character string of 15 bytes once in 3 seconds.
int clientfd = -1;
int dummyfd = -1;
int maxfd = -1;
struct sockaddr_in server_addr;
char recv_buf[100] = {0};
int msg_len = 0;
int bytes_recv = 0;
fd_set readfd;
int retval = 0;
/* Open the socket and a dummy socket */.
clientfd = socket(AF_INET, SOCK_STREAM, 0);
dummyfd = socket(AF_INET, SOCK_STREAM, 0);
if(-1 == clientfd || -1 == dummyfd)
{
perror("socket error: ");
exit(1);
}
printf("Socket opened : %d\n", clientfd);
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(10000);
//server_addr.sin_addr.s_addr = INADDR_ANY;
inet_aton("127.0.0.1", &(server_addr.sin_addr));
memset(&(server_addr.sin_zero), 0, 8);
/* Connect to server */
if(connect(clientfd, (struct sockaddr *)&server_addr, sizeof(struct sockaddr)))
{
perror("connect error: ");
exit(1);
}
printf("Connect Success\n");
maxfd = (clientfd > dummyfd) ? (clientfd + 1) : (dummyfd + 1);
while(1)
{
FD_ZERO(&readfd);
FD_SET(clientfd, &readfd);
FD_SET(dummyfd, &readfd);
printf("Wait on select\n");
retval = select(maxfd , &readfd, NULL, NULL, NULL);
if(retval <= 0)
{
printf("select failed\n");
}
else
{
printf("Wait on recv\n");
/* ... The process waits here ... */
bytes_recv = recv(clientfd, recv_buf, 100, 0);
printf("%d: Bytes recv = %d\t%s\n", retval, bytes_recv, recv_buf);
memset(recv_buf, 0 ,100);
}
}
close(clientfd);
return 0;
}
Edit: Without dummyfd, the program works as intended.
A follow up question:
When the server is closed abruptly, how to detect this using select()?
Can the program be modified so that is blocks on select() when the server side, say, crashes?
Use the following to be sure it's the clientfd that's returning from the select:
else if (FD_ISSET(clientfd, &readfd)) {
Don't have time to test, but I suspect the dummyfd is returning as an EOF from the select, not the clientfd.
After select() returns, you will want to conditionally receive from clientfd. My guess is that there may be data on dummyfd that is triggering the select to complete, but the receive is on the clientfd.
retval = select(maxfd , &readfd, NULL, NULL, NULL);
if(retval <= 0)
{
printf("select failed\n");
}
else
{
if (FD_ISSET(clientfd, &readfd))
{
bytes_recv = recv(clientfd, recv_buf, 100, 0);
...
}
if (FD_ISSET(dummyfd, &readfd))
{
/* "dummyfd" processing */
}