c TCP socket connection refused for localhost - c

I'm trying to make a client/server program in localhost but the client can not connect to the server and I do not know what I'm doing wrong.
I have tried to debug the program and all the parameters seem to be ok.The server does bind, connect, listen and accept.
With the client code a get connect: Invalid argument error. Client (I'm calling the client from the console with ./client localhost):
#include <netinet/in.h>
#include <netdb.h>
#include <string.h>
#include <stdio.h>
#include <errno.h>
int main(int argc, char * argv[])
{
int cd;
struct hostent *hp;
struct sockaddr_in s_ain;
unsigned char byte;
hp = gethostbyname(argv[1]);
bzero((char *)&s_ain, sizeof(s_ain));
s_ain.sin_family = AF_INET;
memcpy(&(s_ain.sin_addr), hp->h_addr, hp->h_length);
s_ain.sin_port = htons(1025);
cd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if( connect(cd, (struct sockaddr*) &s_ain, sizeof(s_ain) == -1) ) {
fprintf(stderr, "connect: %s\n", strerror(errno));
return -1;
}
printf("%s\n", "IT WORKS!");
close(cd);
return 0;
}
Server:
#include <netinet/in.h>
#include <netdb.h>
#include <string.h>
#include <stdio.h>
int main(void)
{
int sd, cd;
socklen_t size;
unsigned char byte;
struct sockaddr_in s_ain, c_ain;
sd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
bzero((char *)&s_ain, sizeof(s_ain));
s_ain.sin_family = AF_INET;s_ain.sin_family = AF_INET;
s_ain.sin_addr.s_addr = INADDR_ANY;
s_ain.sin_port = htons(1025);
if(bind(sd, (struct sockaddr *)&s_ain, sizeof(s_ain)) == -1) {
fprintf(stderr, "%s\n", "err bind");
return -1;
}
if(listen(sd, 5) == -1) {
fprintf(stderr, "%s\n", "err listen");
return -1;
}
while(1) {
size = sizeof(c_ain);
cd = accept(sd, (struct sockaddr *)&c_ain, &size);
printf("%s\n", "IT WORKS !");
}
}

Either you have a typo in your example, or
if( connect(cd, (struct sockaddr*) &s_ain, sizeof(s_ain) == -1) ) {
fprintf(stderr, "%s\n", "err connect");
return -1;
}
has wrong parenthesis. Currently you will call connect with socklen_t addrlen as 0. It should read
if( connect(cd, (struct sockaddr*) &s_ain, sizeof(s_ain)) == -1) {
fprintf(stderr, "%s\n", "err connect");
return -1;
}

Some fixes in server.c
#include <netinet/in.h> // fix
#include <sys/types.h>
#include <netdb.h>
#include <string.h>
#include <stdio.h>
int main(void)
{
int sd, cd;
unsigned char byte;
struct sockaddr_in c_ain;
sd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
bzero((char *)&c_ain, sizeof(c_ain));
c_ain.sin_family = AF_INET;
c_ain.sin_addr.s_addr = INADDR_ANY;
c_ain.sin_port = htons(1025);
bind(sd, (struct sockaddr *)&c_ain, sizeof(c_ain));
listen(sd, 5);
struct sockaddr_in t_ain;
while(1) {
int size = sizeof(t_ain); // < fix
cd = accept(sd, (struct sockaddr *)&t_ain, (socklen_t*)&size); // < fix
printf("%s\n", "IT WORKS !");
}
}
Also to test server you can use telnet:
telnet 127.0.0.1 1025

Related

Check if UDP port is open with ICMP in C

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.

Socket Program in C++ to send a message back and forth between server and client

I am Trying to make a C/C++ Project using Socket Programming.
For this I need Client and Server to sent a index of array back and forth to each other.
So Client will next a index of array and server will sent another index of array until the game is over. (Yeah we are trying to make a game.)
I have written (copied from gfg) code for it but it's not working properly.
The Server for some reason didn't receive the second message. So, We kind of stuck in a deadlock.
Any idea what I did wrong??
Server.cpp
#include <unistd.h>
#include <stdio.h>
#include <sys/socket.h>
#include <stdlib.h>
#include <netinet/in.h>
#include <string.h>
#define PORT 8080
#include <iostream>
#include <stdlib.h>
using namespace std;
int main()
{
int server_fd, new_socket, valread;
struct sockaddr_in address;
int opt = 1;
int addrlen = sizeof(address);
char buffer[1024] = {0};
char *msg = "0";
// Creating socket file descriptor
if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0)
{
perror("socket failed");
exit(EXIT_FAILURE);
}
// Forcefully attaching socket to the port 8080
if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT,
&opt, sizeof(opt)))
{
perror("setsockopt");
exit(EXIT_FAILURE);
}
address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons( PORT );
// Forcefully attaching socket to the port 8080
if (bind(server_fd, (struct sockaddr *)&address,
sizeof(address))<0)
{
perror("bind failed");
exit(EXIT_FAILURE);
}
if (listen(server_fd, 3) < 0)
{
perror("listen");
exit(EXIT_FAILURE);
}
if ((new_socket = accept(server_fd, (struct sockaddr *)&address,
(socklen_t*)&addrlen))<0)
{
perror("accept");
exit(EXIT_FAILURE);
}
int i=0;
while(i<10)
{
valread = read( new_socket , buffer, 1024);
printf("%s\n",buffer );
send(new_socket , msg , strlen(msg) , 0 );
printf("Message sent\n");
i++;
}
return 0;
}
Client.cpp
#include <stdio.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>
#define PORT 8080
#include <iostream>
#include <stdlib.h>
using namespace std;
int main()
{
int sock = 0, valread;
struct sockaddr_in serv_addr;
char *msg="0";
char buffer[1024] = {0};
if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0)
{
printf("\n Socket creation error \n");
return -1;
}
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(PORT);
// Convert IPv4 and IPv6 addresses from text to binary form
if(inet_pton(AF_INET, "127.0.0.1", &serv_addr.sin_addr)<=0)
{
printf("\nInvalid address/ Address not supported \n");
return -1;
}
if (connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0)
{
printf("\nConnection Failed \n");
return -1;
}
int i=0;
while(i<10)
{
send(sock , msg , strlen(msg) , 0 );
printf("Message sent\n");
valread = read( sock , buffer, 1024);
printf("%s\n",buffer );
i++;
}
return 0;
}
Edit: It will be really nice if somebody can tell me how to sent an integer instead of a string.

How to connect to a server using only its IP?

I'm kind of new to sockets. So I setup a server and I want to connect a client to it through the internet. I don't understand what I'm doing wrong because the following example works with the loopback address (127.0.0.1) but not when someone else tries to connect to my server using my external IP address. Is it just not that simple or am I doing something wrong in my code?
Edit: (The client specifically gets stuck when it reaches connect() giving a connect: Connection timed out error)
Edit2: I tried using my broadcast address inet_addr("192.168.1.255") instead of INADDR_ANY in the server code. No change.
This is my server code:
#include <stdio.h>
#include <stdlib.h\
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
int main(void) {
int temp;
struct sockaddr_in my_addr;
struct sockaddr_in their_addr;
int sin_size;
int numbytes;
char buf[100];
int sock_fd; // server file descriptor
int new_fd; // client file descriptor
sock_fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (sock_fd == -1) { perror("socket"); exit(1); }
my_addr.sin_family = AF_INET;
my_addr.sin_port = htons(9000);
my_addr.sin_addr.s_addr = INADDR_ANY;
bzero(&(my_addr.sin_zero), 8);
temp = bind(sock_fd, (struct sockaddr*)&my_addr, sizeof(struct sockaddr));
if (temp == -1) { perror("bind"); exit(1); }
temp = listen(sock_fd, 5);
if (temp == -1) { perror("listen"); exit(1); }
printf("\nListening for new connections on port %d ...\n\n", 9000);
while (1) {
sin_size = sizeof(struct sockaddr_in);
new_fd = accept(sock_fd, (struct sockaddr*)&their_addr, &sin_size);
if (new_fd == -1) { perror("accept"); continue; }
printf("Got connection from IP (%s)\n", inet_ntoa(their_addr.sin_addr));
close(new_fd);
}
}
This is my client code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <netinet/in.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
int main(int argc, char *argv[]) {
int temp;
struct hostent *host_info;
struct sockaddr_in serv_addr;
char ip_addr[100];
int numbytes;
char buf[100];
int sock_fd;
inet_pton(AF_INET, argv[5], &serv_addr.sin_addr);
host_info = gethostbyaddr(&serv_addr.sin_addr, sizeof serv_addr.sin_addr, AF_INET);
if (host_info == NULL) { herror("gethostbyname"); exit(1); }
printf("\nServer: '%s' (IP: %s , Port: %d)\n\n", argv[1], inet_ntop(AF_INET, host_info->h_addr, ip_addr, 100), 9000);
sock_fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (sock_fd == -1) { perror("socket"); exit(1); }
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(9000);
serv_addr.sin_addr = *((struct in_addr *)host_info->h_addr);
bzero(&(serv_addr.sin_zero), 8);
temp = connect(sock_fd, (struct sockaddr*)&serv_addr, sizeof(struct sockaddr));
if (temp == -1) { perror("connect"); exit(1); }
close(sock_fd);
exit(0);
}
Posting an answer here so I can accept my overall solution. The problem was that I had not forwarded a port on my router as #AdamRosenfield indicated, then after I did that I changed my server's address to:
my_addr.sin_addr.s_addr = inet_addr("192.168.1.2");
which is MY local IP address according to ifconfig (I am using Ubuntu).
Now my only problem is that anyone else can connect to my server except me from my own pc, but that might be a problem specific to my router according to #nos.
If anyone has an answer on how to fix that please update me (I tried connecting a client using the loopback address, my external IP, my local IP and a few more, nothing worked).
the client.c should be as below
int main(int argc, char *argv[]){
int temp;
struct hostent *host_info;
struct sockaddr_in serv_addr;
char ip_addr[100];
int numbytes;
char buf[100];
int sock_fd;
unsigned long inaddr;
//inet_pton(AF_INET, argv[5], &serv_addr.sin_addr);
//host_info = gethostbyaddr(&serv_addr.sin_addr, sizeof serv_addr.sin_addr, AF_INET);
//if (host_info == NULL) { herror("gethostbyname"); exit(1); }
printf("\nServer: '%s' (IP: %s , Port: %d)\n\n", argv[0], argv[1], 9000);
inaddr = inet_addr(argv[1]);
sock_fd = socket(AF_INET, SOCK_STREAM, 0);
if (sock_fd == -1) { perror("socket"); exit(1); }
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(9000);
memcpy(&serv_addr.sin_addr, &inaddr, sizeof(inaddr));
//bzero(&(serv_addr.sin_zero), 8);
temp = connect(sock_fd, (struct sockaddr*)&serv_addr, sizeof(struct sockaddr));
if (temp == -1) { perror("connect"); exit(1); }
close(sock_fd);
exit(0);
}
then use g++ compile it:g++ client.c -o client.
use client like this:./client yourserverIP
when set the server address in client code, you can do like this:
serv_addr.sin_addr.s_addr = inet_addr("127.0.0.1");//your server's ip address

Socket Programming

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

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