Hello i have some problem with threads and client and server implementation, i created 2 clients that write on the socket infinite numbers.
to managed the 2 client in the sever.c i create threads everytime a new connection is accept.
it runs but if one client run it works but if i run the second one the first interrupted itself; how can i printf alternately ?
i would like : G1
G2
G1 etc
G1.
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <sys/types.h>
#include <sys/time.h>
#include <sys/wait.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <signal.h>
#include <time.h>
void error(char *msg)
{
perror(msg);
exit(0);
}
struct message { //dichiarazione struct
time_t timestamp;
char g; //process identifier
int x;
};
int main(int argc, char *argv[])
{
int sockfd, portno, n,i;
struct message m1;
struct sockaddr_in serv_addr;
struct hostent *server;
struct timespec delay;
delay.tv_sec = 1;
delay.tv_nsec = 0; //in microseconds
long int offset=1000000;
struct timeval tv;
char buffer[256];
if (argc < 3) {
fprintf(stderr,"usage %s hostname port\n", argv[0]);
exit(0);
}
portno = atoi(argv[2]);
sockfd = socket(AF_UNIX, SOCK_STREAM, 0);
if (sockfd < 0)
error("ERROR opening socket");
server = gethostbyname(argv[1]);
if (server == NULL) {
fprintf(stderr,"ERROR, no such host\n");
exit(0);
}
bzero((char *) &serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_UNIX;
bcopy((char *)server->h_addr,
(char *)&serv_addr.sin_addr.s_addr,
server->h_length);
serv_addr.sin_port = htons(portno);
if (connect(sockfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr)) < 0)
error("ERROR connecting");
while(1){
m1.timestamp=time(NULL);
m1.x=i;
m1.g=getpid();
n = write(sockfd,&m1,sizeof(m1));
if (n < 0)
error("ERROR writing to socket");
i++;
delay.tv_nsec=offset+rand()%offset;
nanosleep(&delay,NULL);
}
return 0;
}`
R.c(server)
#include<stdio.h>
#include<stdlib.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<string.h>
#include <arpa/inet.h>
#include <fcntl.h> // for open
#include <unistd.h> // for close
#include<pthread.h>
struct message { //dichiarazione struct
time_t timestamp;
char g; //process identifier
int x;
};
struct message client_message;
char buffer[1024];
static void * socketThread(void *arg)
{
while(1) {
int newSocket = *((int *)arg);
recv(newSocket , &client_message , sizeof(client_message), 0);
printf("message %d %d %ld\n",client_message.x,client_message.g,client_message.timestamp);
fflush(stdout);
sleep(1);
}
}
int main(){
int serverSocket, newSocket;
struct sockaddr_in serverAddr;
struct sockaddr_storage serverStorage;
socklen_t addr_size;
//Create the socket.
serverSocket = socket(AF_UNIX, SOCK_STREAM, 0);
// Configure settings of the server address struct
// Address family = Internet
serverAddr.sin_family = AF_UNIX;
//Set port number, using htons function to use proper byte order
serverAddr.sin_port = htons(6005);
//Set IP address to localhost
serverAddr.sin_addr.s_addr = inet_addr("127.0.0.1");
//Set all bits of the padding field to 0
memset(serverAddr.sin_zero, '\0', sizeof serverAddr.sin_zero);
//Bind the address struct to the socket
bind(serverSocket, (struct sockaddr *) &serverAddr, sizeof(serverAddr));
//Listen on the socket, with 40 max connection requests queued
if(listen(serverSocket,50)!=0)
{
printf("Error\n");
return -1;
}
printf("Listening\n");
pthread_t tid[60];
int i = 0;
while(1)
{
//Accept call creates a new socket for the incoming connection
addr_size = sizeof serverStorage;
newSocket = accept(serverSocket, (struct sockaddr *) &serverStorage, &addr_size);
//for each client request creates a thread and assign the client request to it to process
//so the main thread can entertain next request
if( pthread_create(&tid[i], NULL, socketThread, &newSocket) != 0 )
printf("Failed to create thread\n");
else
++i;
}
return 0;
}
Thanks !
As I understand in server code in thread function socketThread() you get value of socket descriptor on each iteration. But when you accept new connection in this address writes new value of new socket descriptor. And after that each thread gets data only from last socket.
You should pass in socketThread() socket descriptor by value (not by a pointer)!
Related
I am trying to check if a specific UDP port is open or not. I am trying to do this by sending UDP packets and checking the ICMP response to see if the UDP port is avaiable or not. What am I doing wrong?
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#include <pthread.h>
#include <arpa/inet.h> /* inet(3) functions */
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <netinet/ip_icmp.h>
#include <netdb.h>
#include <unistd.h>
#include <sys/time.h>
#include <stdio.h>
#include <errno.h>
#define MAXLINE 10096
int main(int argc, char **argv)
{
int sockfd, portno;
struct sockaddr_in servaddr;
struct hostent *server;
int sendfd, recvfd;
server = gethostbyname(argv[1]);
if (server == NULL)
{
fprintf(stderr,"ERROR, no such host\n");
exit(EXIT_FAILURE);
}
//socket varibles
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
bcopy((char *)server->h_addr, (char *)&servaddr.sin_addr.s_addr, server->h_length);
//get port from command line arguments
portno = atoi(argv[2]);
servaddr.sin_port = htons(portno);
inet_pton(AF_INET, argv[1], &servaddr.sin_addr);
// open send UDP socket
if((sendfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0)
{
perror("*** socket(,,IPPROTO_UDP) failed ***n");
exit(-1);
}
// open receive ICMP socket
if((recvfd = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP)) < 0)
{
perror("*** socket(,,IPPROTO_ICMP) failed ***n");
exit(-1);
}
int n;
char sendline[] = "a message"; //string for message to be sent
char recvline[MAXLINE]; //string for message to be received
//send ping request
if(sendto(sendfd, sendline, sizeof(sendline), 0, (struct sockaddr *) &servaddr, sizeof(servaddr)) < 0)
{
perror("*** sendto() failed ***");
}
struct timeval tv;
tv.tv_sec = 1;
tv.tv_usec = 100000;
if (setsockopt(recvfd, SOL_SOCKET, SO_RCVTIMEO,&tv,sizeof(tv)) < 0) {
perror("Error");
}
n = recvfrom(recvfd, recvline, MAXLINE, 0, NULL, NULL);
recvline[n] = '\0'; /* null terminate */
struct iphdr *ip_hdr = (struct iphdr *)recvline;
int iplen = ip_hdr->ihl << 2;
struct icmphdr *icmp = (struct icmphdr *)((char *)ip_hdr + (4 * ip_hdr->ihl));
if((icmp->type == ICMP_UNREACH) && (icmp->code == ICMP_UNREACH_PORT))
{
printf("\nPORT CLOSED\n");
}
else
{
printf("\nPORT OPEN\n");
}
exit(0);
}
How can I get this working? When I run the code, It always says "PORT OPEN" in every port I test it with which definitely cannot be right.
So I'm having an issue with a basic server I wrote with C. Every time I try to send less than 6 bytes to a client, the client never displays the bytes I send. There's no failure on the send() call. I've tested this on CURL and Postman, and can't get a response on either.
I cut my program down to the relevant bits, so the struct you see doesn't do anything here.
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
void exit_with_error(const char *err);
#define MSG_SIZE 1028
typedef struct list_s
{
struct list_s *next;
char *title;
char *description;
int id;
} list_t;
int main(void)
{
char *client_name, msg[MSG_SIZE];
int server_socket, client_socket, r, id_count = 0, v = 1;
short server_port = 8080;
struct sockaddr_in server_addr, client_addr;
socklen_t client_addr_len;
list_t *todo_list = NULL;
server_socket = socket(PF_INET, SOCK_STREAM, 0);
if (server_socket < 0)
exit_with_error("socket() failed");
if (setsockopt(server_socket, SOL_SOCKET, SO_REUSEADDR, &v, sizeof(v)) < 0)
exit_with_error("setsockopt() failed");
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(server_port);
server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
if (bind(server_socket, (struct sockaddr *)&server_addr,
sizeof(server_addr)) < 0)
exit_with_error("bind() failed");
if (listen(server_socket, 64) < 0)
exit_with_error("listen() failed");
printf("Server listening on port %d\n", server_port);
fflush(NULL);
while (1)
{
client_addr_len = sizeof(client_addr);
client_socket = accept(server_socket, (struct sockaddr *)&client_addr,
&client_addr_len);
if (client_socket < 0)
exit_with_error("accept() failed");
client_name = inet_ntoa(client_addr.sin_addr);
printf("%s ", client_name);
if (send(client_socket, "[", strlen("["), 0) < 0)
exit_with_error("send() failed");
close(client_socket);
}
close(server_socket);
return (0);
}
void exit_with_error(const char *err)
{
fprintf(stderr, "%s\n", err);
exit(1);
}
I figured it out -- #DanielStenberg was right. Apparently, once I send a message with the correct status-line and content-length header, the body data can be sent in a different send() call.
i am not able to understand why the code is not working. sendall and revcall are taken from beej guide. Their is no output when i send the data from server to client. Can someone please explain the error in code. It is mostly from beej guide.One of the problems in broken pipe i.e reading when port is closed but when the port is closed i am not able to understand.
server code
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#define MAX_SIZE 50
void error(const char *msg)
{
perror(msg);
exit(1);
}
/* sends all data - thanks to Beej's Guide to Network Programming */
int sendall(int s, char *buf, int *len)
{
int total=0;
int bytesleft=*len;
int n=0;
/* send all the data */
while(total<*len)
{
/* send some data */
n=send(s,buf+total,bytesleft,0);
/* break on error */
if(n==-1)
break;
/* apply bytes we sent */
total+=n;
bytesleft-=n;
}
/* return number of bytes actually send here */
*len=total;
/* return -1 on failure, 0 on success */
return n==-1?-1:0;
}
int main(int argc, char *argv[])
{
int sockfd, newsockfd, portno;
socklen_t clilen;
char buffer[256];
struct sockaddr_in serv_addr, cli_addr;
int n;
if (argc < 2)
{
fprintf(stderr,"ERROR, no port provided\n");
exit(1);
}
sockfd = socket(AF_INET, SOCK_STREAM, 0);
printf("sockfd : %d",sockfd);
if (sockfd < 0)
error("ERROR opening socket");
bzero((char *) &serv_addr, sizeof(serv_addr));
portno = atoi(argv[1]);
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = htons(portno);
if(bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0)
error("ERROR on binding");
listen(sockfd,5);
clilen = sizeof(cli_addr);
newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen);
if (newsockfd < 0)
error("ERROR on accept");
char msg[1024] = "hello";
int len = sizeof(msg);
int xx = sendall(sockfd,(char*)msg,&len);
close(newsockfd);
close(sockfd);
return 0;
}
client code
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include<errno.h>
void error(const char *msg)
{
perror(msg);
exit(0);
}
/* receives all data - modelled after sendall() */
int recvall(int s, char *buf, int *len, int timeout)
{
int total=0;
int bytesleft=*len;
int n=0;
time_t start_time;
time_t current_time;
/* clear the receive buffer */
bzero(buf,*len);
time(&start_time);
/* receive all data */
while(total<*len)
{
/* receive some data */
n=recv(s,buf+total,bytesleft,0);
/* no data has arrived yet (non-blocking socket) */
if(n==-1 && errno==EAGAIN)
{
time(¤t_time);
if(current_time-start_time>timeout)
break;
sleep(1);
continue;
}
/* receive error or client disconnect */
else if(n<=0)
break;
/* apply bytes we received */
total+=n;
bytesleft-=n;
}
/* return number of bytes actually received here */
*len=total;
/* return <=0 on failure, bytes received on success */
return (n<=0)?n:total;
}
int main(int argc, char *argv[])
{
int sockfd, portno, n;
struct sockaddr_in serv_addr;
struct hostent *server;
char buffer[1024];
if (argc < 3)
{
fprintf(stderr,"usage %s hostname port\n", argv[0]);
exit(0);
}
portno = atoi(argv[2]);
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
error("ERROR opening socket");
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = inet_addr("127.0.0.1");;
serv_addr.sin_port = htons(portno);
if (connect(sockfd,(struct sockaddr *) &serv_addr,sizeof(serv_addr)) < 0)
error("ERROR connecting");
int m = 1024;
n = recvall(sockfd, buffer,&m,10);
if (n < 0)
error("ERROR reading from socket");
printf("%s\n",buffer);
close(sockfd);
return 0;
}
'int xx = sendall(sockfd,(char*)msg,&len);'
'sockfd' is the server listening socket. You should be calling sendall() with 'newsockfd', as returned by the accept() call.
I have a simple server and a client. I run the server at some port in my machine and when I try to connect my client to the server, it says network is unreachable. Can someone please suggest me why is it not being able to connect to the server. Please have a look at the files below:
server.c
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <netinet/in.h>
void error(const char *msg)
{
perror(msg);
exit(1);
}
int main(int argc, char *argv[]){
int sockfd, newsockfd, portno;
struct sockaddr_in serv_addr;
char sendmessage[50];
if(argc != 2){
fprintf(stderr, "ERROR, Port number not provided or Command line argument is not 2\n");
exit(1);
}
//creating a socket for the server
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if(sockfd < 0){
error("ERROR opening socket");
}
portno = atoi(argv[1]);
//describing the attributes for socket address
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = htons(portno);
if(bind(sockfd, (struct sockaddr*) &serv_addr, sizeof(serv_addr)) < 0){
error("Error on binding the socket");
exit(1);
}
//allowing only 1 client to connect to the server at a time
if(listen(sockfd, 1) < 0){
error("Error in listening to the socket");
}
printf("Server is running...... \nWaiting for the connection from the client on port: %d\n", portno);
while(1){
//accepts the connection from the client
newsockfd = accept(sockfd, (struct sockaddr*)NULL, NULL);
if(newsockfd < 0){
error("Error on accepting");
}
strcpy(sendmessage, "Welcome to The Server");
write(newsockfd, sendmessage, strlen(sendmessage));
}
return 0;
}
client.c
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
void error(const char *msg)
{
perror(msg);
exit(0);
}
int main(int argc, char* argv[]){
int sockfd;
char recvmessage[100];
char sendmessage[100];
int portno;
struct hostent *server;
struct sockaddr_in serv_addr;
if(argc != 3){
fprintf(stderr, "Error, either IP address or port number not provided.\n");
exit(1);
}
portno = atoi(argv[2]);
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if(socket < 0){
error("Error with creating a socket");
}
//check whether the host exist or not
server = gethostbyname(argv[1]);
if(server == NULL){
fprintf(stderr, "ERROR, the host is not defined\n");
exit(0);
}
//creating the socket
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(portno);
serv_addr.sin_addr.s_addr = inet_addr(argv[1]);
//connecting the client to the socket
if(connect(sockfd, (struct sockaddr*) &serv_addr, sizeof(serv_addr)) < 0){
error("Could not connect to the server......");
exit(1);
}
printf("Connection Successful to the Server\n");
return 0;
}
First of all make sure you pass the same port number to both server & client. If the port number is different, communication between server and client won't happen.
Here is the code for local machine. You can change the code a little and pass IP addresses.
Server.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#define PORTNUM 2348
#define bufferLength 500
int main(int argc, char *argv[])
{
char buffer[bufferLength];
struct sockaddr_in dest; /* socket info about the machine connecting to us */
struct sockaddr_in serv; /* socket info about our server */
int mysocket; /* socket used to listen for incoming connections */
socklen_t socksize = sizeof(struct sockaddr_in);
memset(&serv, 0, sizeof(serv)); /* zero the struct before filling the fields */
serv.sin_family = AF_INET; /* set the type of connection to TCP/IP */
serv.sin_addr.s_addr = htonl(INADDR_ANY); /* set our address to any interface */
serv.sin_port = htons(PORTNUM); /* set the server port number */
mysocket = socket(AF_INET, SOCK_STREAM, 0);
/* bind serv information to mysocket */
bind(mysocket, (struct sockaddr *)&serv, sizeof(struct sockaddr));
/* start listening, allowing a queue of up to 1 pending connection */
listen(mysocket, 1);
int consocket;
int cpid;
while(1)
{
consocket = accept(mysocket, (struct sockaddr *)&dest, &socksize);
perror("consocket\n");
if( (cpid = fork()) == 0 )
{
printf("inside child process\n\n\n");
close(mysocket);
close(consocket);
int recivedBytes = recv(consocket, buffer, bufferLength, 0);
buffer[recivedBytes] = '\0';
printf("recieved data %s \n", buffer);
return 0;
}
else
close(consocket);
}
close(mysocket);
return EXIT_SUCCESS;
}
Client.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#define MAXRCVLEN 500
#define PORTNUM 2348
int main(int argc, char *argv[])
{
char buffer[] = "My name is khan"; /* +1 so we can add null terminator */
int len, mysocket;
struct sockaddr_in dest;
mysocket = socket(AF_INET, SOCK_STREAM, 0);
memset(&dest, 0, sizeof(dest)); /* zero the struct */
dest.sin_family = AF_INET;
dest.sin_addr.s_addr = inet_addr("127.0.0.1"); /* set destination IP number */
dest.sin_port = htons(PORTNUM); /* set destination port number */
connect(mysocket, (struct sockaddr *)&dest, sizeof(struct sockaddr));
len = send(mysocket, buffer, strlen(buffer), 0);
perror("len\n");
/* We have to null terminate the received data ourselves */
buffer[len] = '\0';
printf("sent %s (%d bytes).\n", buffer, len);
close(mysocket);
return EXIT_SUCCESS;
}
Hope this helps
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