C - Sockets. client: connect: No such file or directory - c

I'm trying to set up a socket connection between a client and server where server creates socket and reads from it and client writes data to a server. Here is my code:
//server.c
/* a server in the unix domain.*/
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <sys/un.h>
#include <stdio.h>
#define SOCKETNAME "mynewsocket"
int main(void){
char buffer[1024];
int n, sock , nsock;
socklen_t len;
struct sockaddr_un name;
if((sock = socket(AF_UNIX, SOCK_STREAM, 0))<0){
perror("server: socket");
exit(1);
}
memset(&name, 0, sizeof(struct sockaddr_un));
name.sun_family = AF_UNIX;
strcpy(name.sun_path, SOCKETNAME);
len = sizeof(name.sun_family) + strlen(name.sun_path);
unlink ( name.sun_path ) ;
if (bind(sock, (struct sockaddr *) &name, SUN_LEN(&name)) < 0) {
perror("server: bind");
exit(1);
}
if (listen(sock, 5) < 0) {
perror("server: listen");
exit(1);
}
if ((nsock = accept(sock, (struct sockaddr *) &name, &len)) < 0) {
perror("server: accept");
exit(1);
}
n=read(nsock,buffer,80);
printf("A connection has been established\n");
write(1,buffer,n);
write(nsock,"I got your message\n",19);
close(nsock);
close(sock);
exit(0);
}
and client...
//client.c
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <sys/un.h>
#include <stdio.h>
#define SOCKETNAME "mynewsocket"
int main(void){
char buffer [1024];
int n, sock, len;
struct sockaddr_un name;
if((sock = socket(AF_UNIX, SOCK_STREAM, 0))<0){
perror("client: socket");
exit(1);
}
memset(&name, 0, sizeof(struct sockaddr_un));
name. sun_family = AF_UNIX;
strcpy(name.sun_path, SOCKETNAME);
len = sizeof(name.sun_family) + strlen(name.sun_path);
unlink ( name.sun_path ) ;
if (connect(sock, (struct sockaddr *) &name, SUN_LEN(&name)) < 0) {
perror("client: connect");
exit(1);
}
printf("Please enter your message: ");
bzero(buffer,82);
fgets(buffer,80,stdin);
write(sock,buffer,strlen(buffer));
n=read(sock,buffer,80);
printf("The return message was\n");
write(1,buffer,n);
close(sock);
exit(0);
}
To run the two programs, compile first and run it like this:
./server &
./client
When I run the two programs, the server executes fine but the client executes with an error saying No such file or directory
Why is that? What is wrong with my code?

unlink ( name.sun_path ) ;
Why do you unlink? This is the rendez-vous point for client&server! The server could create this file on the file system once it starts running , and unlink it when it exits. (but that is not needed)
The client uses the file to find the server. (te "secret" they share is the location and name of the socket-file.
AF_UNIX uses the file system as a namespace(filenames instead of ip-addresses+portnumbers) Internally, (most probably) the {dev_id,inodenumber} are used as "key" to identify the socket/file-descriptor

Related

Can't connect with my server on different PC using sockets TPC in C

I'm working on a client / server program using sockets. The server just listen for connections and prints it's username. The client tries to find the server and sends it's username. When you run the client, you have to pass three arguments: Your username, the IP address and the port.
The program works fine on same computer, but when I try to connect on a different PC, it can't connect. After a while, it prints "Error connecting to host.".
I am doing something wrong?
Thanks!
Edit: Just one more info. My desktop (server) is on tethed USB internet connection, provided from my smartphone. The client is on Wi-Fi.
Edit2: Now the desktop is on cable and the notebook (client) is on Wi-Fi. Internet conection is up on both devices. I still can't connect. Connection timeout is the error.
Edit3: Well, now I connected both devices on wired (same router) and I connected fine. Seems I have to send an email to IT department of my uni.
client.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <dirent.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#define PORT 4000
#define WORD_SIZE 256
int main(int argc, char * argv[]) {
pthread_t tid;
int sockfd;
struct sockaddr_in serv_addr;
struct hostent * server;
if (argc != 4)
{
printf("Not enough arguments, please inform:\n");
printf("<username> <server_ip_adress> <port>");
return -1;
}
char username[WORD_SIZE], server_ip[WORD_SIZE], port[WORD_SIZE];
strcpy(username, argv[1]);
strcpy(server_ip, argv[2]);
strcpy(port, argv[3]);
server = gethostbyname(server_ip);
if (server == NULL)
{
printf("Error: no such host\n");
return -1;
}
if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
{
printf("Error opening socket\n");
return -1;
}
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(PORT);
serv_addr.sin_addr = * ((struct in_addr * ) server->h_addr);
bzero( & (serv_addr.sin_zero), 8);
int status = connect(sockfd, (struct sockaddr * ) & serv_addr, sizeof(serv_addr));
if (status < 0)
{
printf("Error connecting to host.\n");
return -1;
}
if (send(sockfd, username, WORD_SIZE, 0) < 0)
{
printf("Error sending username.\n");
close(sockfd);
return -1;
}
printf("Username sent.\n");
close(sockfd);
return 0;
}
server.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#define PORT 4000
#define WORD_SIZE 256
int main(int argc, char *argv[])
{
int serverSockfd;
socklen_t clilen;
struct sockaddr_in serv_addr, cli_addr;
if ((serverSockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
printf("Error creating the socket.\n");
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(PORT);
serv_addr.sin_addr.s_addr = INADDR_ANY;
if (bind(serverSockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0)
{
printf("Error binding the socket.\n");
return -1;
}
if (listen(serverSockfd, 5) < 0)
{
printf("Error on listening.\n");
return -1;
}
int newSockfd;
while (1)
{
newSockfd = accept(serverSockfd, (struct sockaddr *)&cli_addr, &clilen);
if (newSockfd < 0)
{
printf("Error on accept a new client.\n");
continue;
}
char username[WORD_SIZE];
if (recv(newSockfd, username, WORD_SIZE, 0) < 0)
{
printf("Error receiving username.\n");
close(newSockfd);
continue;
}
printf("User %s logged in.\n", username);
close(newSockfd);
}
}

C socket : connect error - invalid argument

I made a simple Process-based parallel socket program.
My client code reaches the connect part and throws an Invalid argument error, and my server doesn't ouput anything. just cursor...
I split the terminal in two to run the code.
I run the code with:
gcc -o p-server p-server.c -Wall
./p-server
gcc -o p-client p-client.c -Wall
The output is
[C] Connecting...
[C] Can't connect to a Server: Invalid argument
p-server.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/types.h>
//#include <sys/wait.h>
#define BUFFSIZE 4096
#define SERVERPORT 7799
int main(void){
int i, j, s_sock, c_sock;
struct sockaddr_in server_addr, client_addr;
socklen_t c_addr_size;
char buf[BUFFSIZE] = {0};
char hello[] = "Hello~ I am Server!\n";
//int option = 1;
//setsockopt(s_sock, SOL_SOCKET, SO_REUSEADDR, &option, sizeof(option));
bzero(&server_addr, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(SERVERPORT);
server_addr.sin_addr.s_addr = inet_addr("10.0.0.131");
s_sock = socket(AF_INET, SOCK_STREAM, 0);
if (bind(s_sock, (struct sockaddr *) &server_addr, sizeof(server_addr)) == -1) {
perror("[S] Can't bind a socket");
exit(1);
}
if(listen(s_sock, 5)) {
perror("[S] Can't listen");
exit(1);
}
c_addr_size = sizeof(client_addr);
for ( i=0; i<3; i++) {
if ((c_sock = accept(s_sock, (struct sockaddr *) &client_addr, sizeof(client_addr))) == -1 ){
perror("[S] Can't accept a connection");
exit(1);
}
printf("[S] Connected: client IP addr=%s port=%d\n", inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port));
//fork
switch(fork()){
case 0:
close(s_sock);
//1. say hello to client
if(send(c_sock, hello, sizeof(hello)+1, 0) == -1) {
perror("[S] Can't send message");
exit(1);
}
printf("[S] I said Hello to Client!\n");
//2. recv msg from client
if(recv(c_sock, buf, BUFFSIZE, 0) == -1) {
perror("[S] Can't receive message");
exit(1);
}
printf("[S] Client says: %s\n", buf);
exit(0);
}
close(c_sock);
}
/*
for(j=0; j<3; j++){
wait(&status);
printf("Patren waits %d\n"), wstatus;
}*/
}
p-client.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define BUFFSIZE 4096
#define SERVERPORT 7799
int main(void){
int c_sock;
struct sockaddr_in server_addr;
socklen_t c_addr_size;
char buf[BUFFSIZE] = {0};
char hello[] = "Hi~I am Client!\n";
if((c_sock = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
perror("socket");
exit(1);
}
bzero(&server_addr, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(SERVERPORT);
server_addr.sin_addr.s_addr = inet_addr("10.0.0.131");
printf("[C] Connecting...\n");
if (connect(c_sock, (struct sockaddr *) &server_addr, sizeof(server_addr) == -1)) {
perror("[C] Can't connect to a Server");
exit(1);
}
printf("[C] connected!\n");
//1. recv msg from server (maybe it's "hello")
if (recv(c_sock, buf, BUFFSIZE, 0) == -1) {
perror("[C] Can't receive message");
exit(1);
}
printf("[C] Server says: %s\n", buf);
//2. say hi to server
if(send(c_sock, hello, sizeof(hello)+1, 0) == -1) {
perror("[C] Can't send message");
exit(1);
}
printf("[C] I said Hi to Server!!\n");
printf("[C] I am going to sleep...\n");
sleep(10);
close(c_sock);
return 0;
}

Client can't receive messages from server?

I'm writing 2 small test programs in C (client/server) and I'm having trouble sending messages from the server to the client (but the other way around works just fine). The server says it sent 20 bytes, but on the client's end it says "failed to receive data". I would appreciate any help, thank you so much! My code is below:
Server:
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <string.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <netinet/in.h>
int main(int argc, char* argv[])
{
int sockfd, client_sockfd;
struct sockaddr_in server;
int reading, fileSize;
int i; //counter
int bytesSent;
char test[20] = "test message\n";
memset(&server, 0, sizeof(server));
server.sin_family = AF_INET;
server.sin_port = htons(atoi(argv[1])); //assign port to listen to
server.sin_addr.s_addr = INADDR_ANY; //IP address
if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) //create socket failed
{
perror("socket");
exit(1);
}
if(bind(sockfd, (struct sockaddr *) &server, sizeof(server)) == -1) //connect server socket to specified port
{
perror("bind call failed");
exit(1);
}
//printf("listening to port %d\n", server.sin_port);
if(listen(sockfd, 5) == -1) //queue size of 5
{
perror("listen call failed");
exit(1);
}
while(1) //infinite loop to process connections from clients
{
client_sockfd = accept(sockfd, NULL, NULL); //accept anything
if(client_sockfd == -1)
perror("accept call failed");
bytesSent = send(client_sockfd, test, 20, 0);
printf("bytes sent: %d\n", bytesSent);
}
close(client_sockfd);
close(sockfd);
return 0;
}
Client:
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <string.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <fcntl.h>
#include <errno.h>
int main(int argc, char* argv[])
{
int sockfd;
struct sockaddr_in server;
struct hostent *server_ip_address;
server_ip_address = gethostbyname("eos-class.engr.oregonstate.edu");
int sent; //number of bytes sent
int received; //number of bytes received
char passedMsg[20]; //holds received message
if(server_ip_address == NULL)
{
fprintf(stderr, "could not resolve server host name\n");
exit(1);
}
memset(&server, 0, sizeof(server));
server.sin_family = AF_INET;
server.sin_port = htons(atoi(argv[3])); //assign port to connect to
memcpy(&server.sin_addr, server_ip_address->h_addr, server_ip_address->h_length);
if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) //create socket failed
{
perror("socket");
exit(1);
}
if(connect(sockfd, (struct sockaddr *) &server, sizeof(server)) == -1) //connect socket to remote address failed
{
printf("tried to connect to port %d\n", server.sin_port);
perror("connect");
exit(1);
}
if((received = recv(sockfd, passedMsg, 20, 0)) < 0);
{
printf("Failed to receive data\n");
exit(1);
}
printf("Received message: %s\n", passedMsg);
close(sockfd);
return 0;
}
In your client code, in the error checking for recv, change printf to perror. If you do, the output will be:
Failed to receive data: Success
So the recv call was successful, but the error code ran anyway. Why? Let's take a closer look at that if statement:
// what's this? ----v
if((received = recv(sockfd, passedMsg, 20, 0)) < 0);
{
printf("Failed to receive data\n");
exit(1);
}
There's a stray ; after the condition in the if statement. This means that the if statement does nothing if the condition is true, and that the following block is not the body of the if but an independent block that always runs.
Get rid of the extra ; and you get the expected results.

Connection refused TCP sockets

I made a simple client and a simple server with TCP sockets.When I was testing them, I got an error message: Connection refused.
I have opened the ports for the server, so I don't understand why I get this error... Can you help me?
This is the client's source
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <errno.h>
#define PORTA 3459
int main()
{
char indirizzo[15];
char buffer[20];
struct sockaddr_in client;
int clients;
puts("Inserire l'indirizzo");
fgets(indirizzo, 15, stdin);
printf("L'indirizzo del destinatario è %s",indirizzo);
puts("Inserire il messaggio");
fgets(buffer, 20, stdin);
client.sin_family = AF_INET;
client.sin_port = htons(PORTA);
client.sin_addr.s_addr = inet_addr(indirizzo);
memset(client.sin_zero, '\0',8);
if((clients = socket(PF_INET, SOCK_STREAM,0)) == -1)
{
printf("%s\n", strerror(errno));
exit(0);
}
if( (connect(clients, (struct sockaddr *)&client, sizeof(structsockaddr)) ) == -1)
{
printf("%s\n", strerror(errno));
exit(0);
}
send(clients, buffer, 20,0);
close(clients);
return 0;
}
This is the server's source code
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <errno.h>
#define PORTA 3459
int main()
{
struct sockaddr_in sock;
int socks;
struct sockaddr_in newsock;
int newsocks;
if((socks = socket(PF_INET, SOCK_STREAM,0)) == -1)
{
puts("Errore: socks non inizializzato\n");
printf("%s\n", strerror(errno));
exit(0);
}
sock.sin_family = AF_INET;
sock.sin_port = htons(PORTA);
sock.sin_addr.s_addr = htonl(INADDR_ANY);
memset(sock.sin_zero, '\0',8);
int si = 1;
if(setsockopt(socks,SOL_SOCKET,SO_REUSEADDR,&si,sizeof(int)) == -1)
{
puts("Errore durante il settaggio del socket\n");
printf("%s\n", strerror(errno));
exit(0);
}
if(bind(socks,(struct sockaddr *)&sock, sizeof(struct sockaddr) ) == -1)
{
puts("Errore durante il binding\n");
printf("%s\n", strerror(errno));
exit(0);
}
char buffer[30];
int lung;
lung = sizeof(newsock);
listen(socks, 5);
if((newsocks = accept(socks,(struct sockaddr *)&newsock,&lung)) == -1)
{
puts("Errore durante l'accettazione del socket remoto\n");
printf("%s\n", strerror(errno));
exit(0);
}
if(recv(newsocks, buffer,sizeof(buffer),0) == -1)
{
puts("Errore durante la ricezione dei dati");
printf("%s\n", strerror(errno));
}
puts(buffer);
return 0;
}
Code looks good in general, except for not controlling errors in some cases (inet_addr) and the ports are the same both in client and server. If you get connetion refused error, it cannot be a firewall-related problem.
Do you have the same error always or sometimes it works OK?
Most probably the problem is one of these:
1-Client is trying to connect to the wrong IP address. Check the address printed and result of inet_addr.
2-The server doesn't have a loop to keep listening for connections. It finishes after getting one connection. Maybe a first test works then server ends and client is run again getting connection refused.
You could also try not setting SO_REUSEADDR. I don't think it's related but if nothing else works ...

Connection refused error in socket programming

This code is generating "Connection Failed error", (the error generating portion is commented below in the code) even when i am supplying the correct input format eg.
./Client ip text portno
./Client 127.0.0.1 "tushar" 7100
//AUTHOR: TUSHAR MAROO
//Client.c
//header files used
#include <stdio.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <netinet/in.h>
//constants
#define RCVBUFFERSIZE 32
//functions used
void DieWithError(char *errorMessage);
//main program
int main(int argc, char *argv[]){
int sock;
struct sockaddr_in serverAddr;
unsigned short serverPort;
char *serverIp;
char *message;
unsigned int messageLength;
char buffer[RCVBUFFERSIZE];
//condition check deplyed for nuber of arguements not for data in arguements
if((argc<3) || (argc>4)){
fprintf(stderr,"Format: %s <Server's IP> <Your Message> <Port Number>\n",argv[0]);
exit(1);
}
serverIp = argv[1];
message = argv[2];
if(argc == 4){
serverPort = atoi(argv[3]);
} else {
serverPort = 7;
}
//create a socket and check success and handle error
if((sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0 )
fprintf(stderr, "Socket Creation Fail");
//server details
//bzero((struct sockaddr_in *)(&serverAddr),sizeof(serverAddr));
memset(&serverAddr, 0, sizeof(serverAddr));
serverAddr.sin_family = AF_INET;
serverAddr.sin_addr.s_addr = inet_addr(serverIp);
serverAddr.sin_port = htons(serverPort);
printf("tusharmaroo");
//not working why??
//if (connect(sock, (struct sockaddr *) &serverAddr, sizeof(serverAddr)) < 0)
//DieWithError("Connection Error..");
//fprintf(stderr,"Connection error");
//this snippet also not working
if (connect(sock, (struct sockaddr *) &serverAddr, sizeof(serverAddr)) < 0)
DieWithError("connect() failed");
printf("connected....");
messageLength = strlen(message);
if(send(sock, message, messageLength, 0) > 0)
printf("message sent....");
close(sock);
exit(0);
}
//AUTHOR TUSHAR MAROO
//SERVER CODE
//header files
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <netinet/in.h>
//constants declared
#define ALLOWEDCONNECTIONS 5
//external functions
void DieWithError(char *error);
void ClientHandle(int sock);
//main code
int main(int argc, char argv[]){
int serverSock;
int clientSock;
struct sockaddr_in serverAddr;
struct sockaddr_in clientAddr;
unsigned int serverPort;
unsigned int clientLength;
if(argc != 2){
fprintf(stderr,"Format: %d <Port No.>", argv[0]);
//DieWithError("Pass Correct Number of Arguements...");
exit(1);
}
if((serverSock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0){
DieWithError("Socket not Created");
exit(1);
}
serverPort = htons((argv[1]));
//assign address to the server
memset(&serverAddr, 0, sizeof(serverAddr));
serverAddr.sin_family = AF_INET;
serverAddr.sin_addr.s_addr = htonl(INADDR_ANY);
serverAddr.sin_port = htons(serverPort);
//socket has been created now bind it to some ip and port
if((bind(serverSock,(struct sockaddr *)&serverAddr,sizeof(serverAddr))) < 0){
DieWithError("Binding Failed");
}
if(listen(serverSock,5) < 0){
DieWithError("Listen Failed");
}
for(;;){
clientLength = sizeof(clientAddr);
if((clientSock = accept(serverSock, (struct sockaddr *) &clientAddr, &clientLength)) < 0){
DieWithError("Accept() failed");
exit(1);
}
printf("Handling Client %s ",inet_ntoa(clientAddr.sin_addr));
}
return 0;
}
This is wrong in the server code
serverPort = htons((argv[1]));
This should be
serverPort = htons(atoi(argv[1]));
Are you sure there are no firewall rules causing troubles for you? Ensure that.
If the connect fails you should be able to print out the error using perror or strerror:
perror("Could not connect:");
works for me
client and server are ubuntu 12.04
for server, run in a shell
nc -l 9999
This is on a host with the address "192.168.56.13"
for client, compile code above with "DieWithError" fixed up
void DieWithError(char *errorMessage) { printf("%s",errorMessage); exit(1); }
cc -o foo foo.c
./foo 192.168.56.13 "hello" 9999</strike>
replace the DieWithError() with perror() Then I would guess that it will print out "connection refused" as you seem to have a networking problem with getting the server running on the correct address.
However, if the address in your client is correct the nc program WILL print "hello"
you just altered your program the previous version worked for me. The current version, I don't know if it does.
Like everyone else is saying, use perror() to get proper diagnostics

Resources