Linux socket not connected

Socket Programming Error in Connect

I am trying to do Socket programming. I’ve google and looked at problems like mine. However, I can’t see to figure out my error. Whenever I run my code, I get an error in connect() in main in client.c . The error is invalid argument . Server.c

/* chatroom server */ #include #include #include #include #include #include #include #include #include #include #include #define MAX_ROOMS 36 #define MAX_NAME_SIZE 56 #define PORT_NUM 12333 #define MSG_SIZE 8 #define MAX_LOAD 246 #define MAX_CRC 64 //max clients #define MAX_BUF 256 #define SERVER_IP 32 #define DEBUG 0 struct msg < int type; //create, join, delete int length; // length or port num >; struct chat_room < int socket_d; //socket descriptor int port; pthread_t id; //id of chatroom char name[MAX_NAME_SIZE]; int clients[MAX_ROOMS]; // used to hold the client's master sockets >; struct chat_room* findRoom(char* name, struct chat_room* chat) < int iterator; for(iterator = 0; iterator < MAX_ROOMS; iterator++)< if(strcmp(name, chat[iterator].name) && (chat[iterator].port != 0)) < return &chat[iterator]; >> //if room does not exist return NULL; > struct chat_room* joinServer(int chat_socket, char* name, struct chat_room* chat)< struct chat_room* local_chat = findRoom(name, chat); int i; if(local_chat != NULL)< //if the chat exists for(i= 0; i< MAX_CRC; i++)< if(local_chat->clients[i] == 0) < local_chat->clients[i] = chat_socket; > return local_chat; > > //if server if full or else error return NULL; > int createResponse(int chat_socket, int new_port_num, int type) < struct msg temp; char temp_buff[MAX_LOAD]; memset(temp_buff, 0, MAX_LOAD); temp.type = type; temp.length = new_port_num; memcpy(temp_buff, &temp, sizeof(temp)); write(chat_socket, temp_buff, MSG_SIZE); return 0; >int joinResponse(int chat_socket, int new_port_num) < struct msg temp; char temp_buff[MAX_LOAD]; memset(temp_buff, 0, MAX_LOAD); temp.type = 11; temp.length = new_port_num; memcpy(temp_buff, &temp, sizeof(temp)); write(chat_socket, temp_buff, MSG_SIZE); return 0; >int deleteResponse(int chat_socket, struct chat_room* chat)< struct msg temp; char temp_buff[MAX_LOAD]; int i; memset(temp_buff, 0, MAX_LOAD); temp.type = 12; memcpy(temp_buff, &temp, sizeof(temp)); for(i=0; iclients[i] != chat_socket) && (chat->clients[i] != 0)) write(chat->clients[i],temp_buff, MSG_SIZE); > return 0; > struct chat_room* addRoom(int chat_socket, char* name, struct chat_room* chat) < int socket_d; int i; struct sockaddr_in sock; static int port = PORT_NUM; memset(&sock, 0, sizeof(sock)); int temp = -1; for(i = 0; ielse if((chat[i].port == 0) && (temp== -1)) < temp = i; >> if(temp == -1) < return NULL; >socket_d = socket(AF_INET, SOCK_STREAM, 0); if(socket_d == -1 && DEBUG) < perror("Error creating chatroom socket"); return NULL; >sock.sin_family = AF_INET; port++; sock.sin_port = htons(port); if(bind(socket_d, (struct sockaddr*)&sock, sizeof(struct sockaddr_in)) == -1) < perror("error in binding "); return NULL; >chat[temp].socket_d = socket_d; chat[temp].port = port; strcpy(chat[temp].name, name); return &chat[temp]; > void* chat_room_main(void* chat_room_cluster) < char buf[MAX_LOAD]; int socket_d, chat_socket; int temp; //temp_fd int read_val; int num_clients = 0; int i; int clients[MAX_CRC]; fd_set allfd, modfd; struct chat_room chat_room_para; memcpy(&chat_room_para, (struct chat_room*)chat_room_cluster, sizeof(struct chat_room)); free(chat_room_cluster); memset(clients, 0, sizeof(int)*MAX_CRC); socket_d = chat_room_para.socket_d; listen(socket_d, 1); FD_ZERO(&allfd); FD_SET(socket_d, &allfd); printf("New Chatroom Started\n"); while(1)< modfd = allfd; select(FD_SETSIZE, &modfd, NULL, NULL, NULL); for(temp = 0; temp < FD_SETSIZE; temp++)< if(FD_ISSET(temp, &modfd))< memset(buf, 0, sizeof(buf)); if(temp == socket_d) < chat_socket = accept(socket_d, NULL, NULL); FD_SET(chat_socket, &allfd); // find an empty spot to add the chat room for(i = 0; i> sprintf(buf, "Number of people in chatroom: %d", num_clients); write(chat_socket, buf, strlen(buf)); num_clients++; > else < if(read_val = read(temp, buf, MAX_LOAD) >0) < for(i = 0; i< MAX_CRC; i++)< if((clients[i] != temp) && (clients[i] != 0))< write(clients[i], buf, read_val); >> > else if(read_val num_clients--; close(chat_socket); > > > > > > int main(int argc, char* argv[]) < int server_socket, chat_socket; //file descriptors for server and chat int temp; //tempfd int i, j; char server_ip[SERVER_IP]; char buf[MAX_BUF]; char msg_buf[MSG_SIZE]; fd_set allfd, modfd; struct sockaddr_in sock; struct hostent* host_name; struct chat_room chatrooms[MAX_ROOMS]; memset(chatrooms, '\0', sizeof(struct chat_room)* MAX_ROOMS); memset(&sock, '\0', sizeof(sock)); server_socket = socket(AF_INET, SOCK_STREAM, 0); if(server_socket == -1)< perror("Error creating socket"); return -1; >sock.sin_family = AF_INET; sock.sin_port = htons(PORT_NUM); sock.sin_addr.s_addr = INADDR_ANY; if((bind(server_socket, (struct sockaddr*)&sock, sizeof(struct sockaddr_in))) == -1) < perror("Error in bind()"); return -1; >listen(server_socket, 1); FD_ZERO(&allfd); FD_SET(server_socket, &allfd); FD_SET(0, &allfd); printf("\n*******Chatroom Server*******"); while(1) < modfd = allfd; select(FD_SETSIZE, &modfd, NULL, NULL, NULL); for(temp = 0; temp < FD_SETSIZE; temp++) < if(FD_ISSET(temp, &modfd)) < switch(temp)< case 0: break; default: if(temp == server_socket)< chat_socket = accept(server_socket, NULL, NULL); >else < char msg_buf[MSG_SIZE]; char buf[MAX_LOAD]; char name[MAX_LOAD]; struct msg temp_message; struct chat_room* local_chat = NULL; void* (*init_chatroom)() = &chat_room_main; void* thread_args; pthread_attr_t attr; pthread_t tid; pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); memset(buf, 0, sizeof(buf)); memset(msg_buf, 0, sizeof(msg_buf)); msg_buf[19]= 0; int read_val = read(temp, msg_buf, MSG_SIZE); if(read_val >0)< memcpy(&temp_message, msg_buf, sizeof(temp_message)); read(temp, buf, temp_message.length - sizeof(temp_message)); memcpy(name, buf, temp_message.length - sizeof(temp_message)); if(temp_message.type == 0) id = tid; createResponse(temp, local_chat->port, 10); > > else if(temp_message.type == 1)< //join local_chat = joinServer(temp, name, chatrooms); if(local_chat != NULL)< joinResponse(temp, local_chat->port); > > else if(temp_message.type == 2)< //delete local_chat = findRoom(name, chatrooms); printf("Deleting Room\n"); if(local_chat != NULL) < local_chat->port = 0; close(local_chat->socket_d); deleteResponse(temp, local_chat); for(j = 0; jclients[j]!=0) < FD_CLR(local_chat->clients[j], &modfd); local_chat->clients[j] = 0; > > pthread_cancel(local_chat->id); > > > else if(read_val > > > > > return 0; > 
#include #include #include #include #include #include #include #include #include #include #define PORT_NUM 12333 #define MSG_SIZE 8 #define MAX_LOAD 246 #define MAX_BUF 256 #define SERVER_IP 32 struct msg < int type; int length; >; struct thread_para < int port; struct hostent* host_name; >; int sendCmd(int chat_socket, char* buf, int type) < //function for sending the command struct msg temp; char temp_buf[MAX_LOAD]; char name[MAX_LOAD]; int iterator; if(type == 0)< iterator = 6; >else if(type == 1) < iterator = 4; >else if(type == 2) < iterator = 6; >for(; iterator < strlen(buf); iterator++)< if(buf[iterator] == ' ') < continue; >else < break; >> strcpy(name, buf+iterator); memset(temp_buf, 0, MAX_LOAD); temp.type = type; temp.length = sizeof(temp)+strlen(name)+1; //for \0 memcpy(temp_buf, &temp, sizeof(temp)); memcpy(temp_buf+sizeof(temp), name, strlen(name)+1); write(chat_socket, temp_buf, temp.length); return 0; > void* connectChat(int port_num, struct hostent* host_name, int master)< char buf[MAX_BUF]; char temp_buf[MAX_BUF]; int chat_socket; int i; int input; int temp; //temp fd fd_set allfd, modfd; struct sockaddr_in sock; printf("Successfully Joined Room\n"); memset(buf, 0, sizeof(buf)); memset(&sock, 0, sizeof(sock)); sock.sin_family = AF_INET; sock.sin_port = htons(port_num); memcpy((char*)&sock.sin_addr.s_addr, host_name->h_addr, host_name->h_length); chat_socket = socket(AF_INET, SOCK_STREAM, 0); if(chat_socket == -1) < perror("Error in creation"); return NULL; >if(connect(chat_socket, (struct sockaddr*)&sock, sizeof(struct sockaddr)) < 0 )< perror("Error in connection"); return NULL; >FD_ZERO(&allfd); FD_SET(chat_socket, &allfd); FD_SET(0, &allfd); FD_SET(master, &allfd); while(1) < modfd = allfd; select(FD_SETSIZE, &modfd, NULL, NULL, NULL); for(temp = 0; temp< FD_SETSIZE; temp++)< memset(buf, 0, sizeof(buf)); memset(temp, 0, sizeof(buf)); if(temp == 0) < //reading from standard in input = read(0, buf, MAX_BUF); buf[input-1] = '\0'; //add termination to end write(chat_socket, buf, strlen(buf)); >else if(temp == chat_socket) < input = read(0, buf, MAX_BUF); buf[input] = '\0'; memcpy(temp, buf, input); //display message printf("%s \n", temp_buf); >else if(temp == master) < struct msg temp_message; input = read(temp, buf, MSG_SIZE); memcpy(&temp_message, buf, MSG_SIZE); if(temp_message.type == 12)< printf("Chatroom has been deleted, Shutting down chatroom\n"); return NULL; >> > > return 0; > int main(int argc, char* argv[]) < char buf[MAX_BUF]; int chat_socket; int i; int input; int temp; //temp fd int accept_input = 1; // take input for stdin to create a chat thread fd_set allfd, modfd; char server_ip[SERVER_IP]; struct hostent* host_name; struct sockaddr_in sock; struct msg temp_message; pthread_attr_t tattr; pthread_t tid; if(argc < 2) < printf("Please try ./crc \n"); return -1; > pthread_attr_init(&tattr); pthread_attr_setdetachstate(&tattr, PTHREAD_CREATE_DETACHED); memset(&sock, '\0', sizeof(sock)); sock.sin_family = AF_INET; sock.sin_port = htons(PORT_NUM); strcpy(server_ip ,argv[1]); if((host_name = (struct hostent*)gethostbyname(server_ip)) == NULL) < perror("failed to get host name"); return -1; >memcpy((char*)&sock.sin_addr.s_addr, host_name->h_addr, host_name->h_length); chat_socket = socket(AF_INET, SOCK_STREAM, 0); if(chat_socket == -1) < perror("Error creating socket"); return -1; >if((connect(chat_socket, (struct sockaddr*)&sock, sizeof(sock))) < 0) < perror("Error connecting"); return -1; >FD_ZERO(&allfd); /* first, clear the allfd set */ FD_SET(chat_socket, &allfd); /* adding client to the set */ FD_SET(0, &allfd); printf("*****Welcome to the Chatroom*****\n"); while(1) < modfd = allfd; select(FD_SETSIZE, &modfd, NULL, NULL, NULL); for(temp = 0; temp < FD_SETSIZE; temp++)< if(FD_ISSET(temp, &modfd))< if(temp == 0)< input = read(0, buf, MAX_BUF); buf[input-1] = '\0'; //remove \n inserts termination if((strncasecmp(buf, "create ", 7) == 0)) < sendCmd(chat_socket, buf, 0); >else if((strncasecmp(buf, "join ", 5) == 0)) < sendCmd(chat_socket, buf, 1); >else if((strncasecmp(buf, "delete ", 7)==0)) < sendCmd(chat_socket, buf, 2); >else < printf("Enter a valid command: create , join , delete \n"); > > else if(temp == chat_socket) < input = read(temp, buf, MSG_SIZE); memcpy(&temp_message, buf, sizeof(temp_message)); if(temp_message.type == 10) < printf("Created Chatroom\n"); >else if(temp_message.type == 11) < connectChat(temp_message.length, host_name, chat_socket); fflush(stdin); >else if(temp_message.type == 15) < printf("Chatroom exits. Type join to join\n"); > > > > > close(chat_socket); return 0; > 

I gave both sets of code just in case it was need. The program is designed to create multiple chat rooms.

Читайте также:  Linux forgotten password root

Источник

Can not connect to Linux «abstract» unix socket

I’m trying to use UNIX sockets for inter-thread communication. The program is only intended to run on Linux. To avoid creating the socket files, I wanted to use «abstract» sockets, as documented in unix(7). However, I don’t seem to be able to connect to these sockets. Everything works if I’m using «pathname» sockets, though. Here is the code (I haven’t quoted any error handling, but it’s done): thread#1:

int log_socket = socket(AF_LOCAL, SOCK_STREAM, 0); struct sockaddr_un logaddr; socklen_t sun_len = sizeof(struct sockaddr_un); logaddr.sun_family = AF_UNIX; logaddr.sun_path[0] = 0; strcpy(logaddr.sun_path+1, "futurama"); bind(log_socket, &logaddr, sun_len); listen(log_socket, 5); accept(log_socket, &logaddr, &sun_len); . // send - receive 
struct sockaddr_un tolog; int sock = socket(AF_LOCAL, SOCK_STREAM, 0); tolog.sun_family = AF_UNIX; tolog.sun_path[0] = 0; strcpy(tolog.sun_path+1, "futurama"); connect(sock, (struct sockaddr*)&tolog, sizeof(struct sockaddr_un)); 

If all I do in the above code, is change the sun_path to not have leading \0, things work perfect. strace output:

t1: socket(PF_FILE, SOCK_STREAM, 0) = 0 t1: bind(0, , 110) t1: listen(0, 5) t2: socket(PF_FILE, SOCK_STREAM, 0) = 1 t2: connect(1, , 110 t2: ) = -1 ECONNREFUSED (Connection refused) t1: accept(0,

I know that the connect comes before accept, that’s not an issue (I tried making sure that accept() is called before connect(), same result. Also, things are fine if the socket is «pathname» anyway).

For communication between threads of the same process, an ordinary pipe(2) should be enough! And you could also use pipes if all the communicating processes and/or threads have the same parent process!

@BasileStarynkevitch pipe will not work in my case. I need multiple threads to send info, and receive a synchronous response before moving on.

Читайте также:  What is linux hpc cluster

@BasileStarynkevitch for this, I will have to know in advance how many maximum pipes to open, or limit access to one using locks. The socket approach has less overhead for such case.

4 Answers 4

While I was posting this question, and re-reading unix(7) man page, this wording caught my attention:

an abstract socket address is distinguished by the fact that sun_path[0] is a null byte (’\0’). All of the remaining bytes in sun_path define the «name» of the socket

So, if I bzero’ed the sun_path before filling in my name into it, things started to work. I figured that’s not necessarily straight-forward. Additionally, as rightfully pointed out by @davmac and @StoneThrow, the number of those «remaining bytes» can be reduced by specifying only enough length of the socket address structure to cover the bytes you want to consider as your address. One way to do that is to use SUN_LEN macro, however, the first byte of the sun_path will have to be set to !0, as SUN_LEN uses strlen .

If sun_path[0] is \0, The kernel uses the entirety of the remainder of sun_path as the name of the socket, whether it’s \0-terminated or not, so all of that remainder counts. In my original code I would zero the first byte, and then strcpy() the socket name into the sun_path at position 1. Whatever gibberish that was in sun_path when the structure was allocated (especially likely to contain gibberish since it’s allocated on the stack), and was included in the length of the socket structure (as passed to the syscalls), counted as the name of the socket, and was different in bind() and connect().

Читайте также:  Kali linux alfa awus

IMHO, strace should fix the way it displays abstract socket names, and display all the sun_path bytes from 1 to whatever the structure length that was supplied, if sun_path[0] is 0

Источник

UNIX socket connection refused

Under OS-X, I’ve got process named ‘listener’ that is waiting on ‘accept’ to read data from local unix socket named listener_socket. unfortunately, any attempt to connect that socket terminate in ‘connection refused’ error. Using lsof, to make sure that the ‘listener’ actually listen to this socket :

sudo lsof -p 570 COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME . listener 570 root 3u unix 0x48a2751a1bad61ef 0t0 /private/var/run/my_sockets/listener_socket 
file /private/var/run/my_sockets/listener_socket /private/var/run/my_sockets/listener_socket: socket 

However, it still fail to connect, even when i’m using an alternative way from command like (using socat command)

sudo socat LOCAL:/private/var/run/my_sockets/listener_socket,interval=1 EXEC:'aaaaaaaaaaaaaaaaa',nofork 2015/11/23 00:57:33 socat[928] E connect(3, LEN=49 AF=1 "/private/var/run/my_sockets/listener_socket", 49): Connection refused 

perhaps there are more i can do to figure out why i cannot send data to the socket, even-though it’s obvious that ‘listener’ waiting for this data on the other side ? here’s the relevant part of my code : sender:

sockfd = socket(PF_UNIX, SOCK_STREAM, 0); address.sun_family = AF_UNIX; snprintf(address.sun_path, UNIX_PATH_MAX, "%s", LISTENER_SOCKET_PATH); connect(sockfd, (struct sockaddr *) &address, sizeof(struct sockaddr_un) write . 
fd = socket(PF_UNIX, SOCK_STREAM, 0); unlink(sock_name); // in case the socket is used before listen(server->fd, 5); // we don't reach 5 listeners for sure . chmod(sock_name, mode); // giving root privilages accept(server->fd, (struct sockaddr *) &server->address, &server->address_length); read . 

Источник

C sockets (Linux) won’t connect

recently I’ve been trying to do a lot with C sockets as it is a language I need for future use. However I’ve encountered this problem I can’t manage to solve. I made both client and server — unfortunately the two binaries refuse to connect in between each other. What I mean is that I do not get any error whatsoever when I run the server binary and client binary in a same machine, but no connection either. Any ideas? Here is the code! (Ubuntu, both C codes compiled with gcc, server and client code ran within the same machine in 2 different terminals.) Server.c:

 #include #include #include #include #include #include //inet_aton(), inet_ntoa() etc #include #include #define PORT 8000 #define ERROR perror("Something went wrong! => "); #define BUFFERSIZE 256 int main() < int sockfd, client_socketfd; int bytes_sent; socklen_t sin_size; struct sockaddr_in server_addr; struct sockaddr_in connectedClient_addr; char message[BUFFERSIZE] = "Welcome to the server!"; if((sockfd = socket(PF_INET, SOCK_STREAM ,0)) == -1) < ERROR; exit(-1); >server_addr.sin_family = AF_INET; server_addr.sin_port = htons(PORT); server_addr.sin_addr.s_addr = INADDR_ANY; //Subject to change if((bind(sockfd, (struct sockaddr *)&server_addr, sizeof(server_addr))) == -1) < ERROR; exit(-2); >if((listen(sockfd, 5)) == -1) < ERROR; exit(-3); >int addrlen = sizeof(connectedClient_addr); if((client_socketfd = accept(sockfd, (struct sockaddr *)&connectedClient_addr, (socklen_t*)&addrlen)) == -1) < ERROR; exit(-4); >printf("Got a connection from: %s at port: %d" , inet_ntoa(connectedClient_addr.sin_addr), PORT); if((send(sockfd, &message, BUFFERSIZE, 0)) == -1) < ERROR; exit(-5); >close(sockfd); close(client_socketfd); return 0; > 
#include #include #include #include #include #include #include #include #define PORT 8000 #define ERROR perror("Something went wrong! =>"); #define BUFFERSIZE 256 int main() < int sockfd; struct sockaddr_in client_addr; char message[BUFFERSIZE] = "Successfully connected!"; int bytes_received, bytes_sent; char buffer[BUFFERSIZE]; if((sockfd = socket(PF_INET, SOCK_STREAM, 0)) == -1) < ERROR; exit(-1); >client_addr.sin_family = AF_INET; client_addr.sin_port = htons(PORT); client_addr.sin_addr.s_addr = INADDR_ANY; if((connect(sockfd, (struct sockaddr*)&client_addr, sizeof(client_addr))) == -1) < ERROR; exit(-2); >if((bytes_received = recv(sockfd, &buffer, BUFFERSIZE, 0)) == -1) < ERROR; exit(-3); >printf("Received %d bytes:\n" , bytes_received); printf("%s", buffer); close(sockfd); return 0; > 

Источник

Оцените статью
Adblock
detector