I'm trying to make a server and client. But when I try to connect the client to the server, I get connection refused. The other answers on stack overflow said to make sure you have listen() and accept(), which I do, and to check the firewalls. So I turned off all the firewalls just to make sure.
I still get connection refused, so I tried ./telnet 10.1.10.13 9696, and got:
Trying 10.1.10.13...
telnet: connect to address 10.1.10.13: Connection refused
telnet: Unable to connect to remote host
Here's the code for the server
int setUpServer(struct fuzzerObj *ptr)
{
/* Declarations */
int hostSocket, yes = 1, rtrn;
union
{
struct sockaddr_in in;
}address;
/* Create Socket */
hostSocket = socket(AF_INET, SOCK_STREAM, 0);
if(hostSocket < 0)
{
errorHandler("Could not create socket\n", FUNCTION_ID_SET_UP_SERVER);
return -1;
}
/* Reuse Address */
rtrn = setsockopt(hostSocket, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
if(rtrn < 0)
{
errorHandler("Couldn't Reuse Address\n", FUNCTION_ID_SET_UP_SERVER);
return -1;
}
errno = 0;
/* Set Up Struct */
address.in.sin_len = sizeof(address.in);
address.in.sin_family = AF_INET;
address.in.sin_port = BBPORT_NUMBER;
address.in.sin_addr.s_addr = htonl(INADDR_ANY);
memset(address.in.sin_zero, 0, sizeof(address.in.sin_zero));
/* Bind Address to Socket */
rtrn = bind(hostSocket, (struct sockaddr*) &address, address.in.sin_len);
if(rtrn < 0)
{
errorHandler("Can't Bind Address to Socket\n", FUNCTION_ID_SET_UP_SERVER);
perror("");
return -1;
}
/* listen */
rtrn = listen(hostSocket, ptr->numberOfClients);
if(rtrn < 0)
{
errorHandler("Can't Listen\n", FUNCTION_ID_SET_UP_SERVER);
return -1;
}
while(1) acceptClient(hostSocket);
return 0;
}
int acceptClient(int fd)
{
struct sockaddr_storage addr;
socklen_t addr_len = sizeof(addr);
int clientFd = accept(fd, (struct sockaddr *) &addr, &addr_len);
if(clientFd < 0)
{
printf("Can't Accept Client\n");
return -1;
}
return clientFd;
}
and the code for the client:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <netinet/in.h>
#include <stdbool.h>
#include <sys/types.h>
#include <unistd.h>
#include <errno.h>
#define BLACKBOX_PORT 9696
int main(int argc, char *argv[])
{
/* Check To See If an argument was passed */
if(argc < 2)
{
printf("No enough Arguments\n");
return -1;
}
/* Declaration's */
const char *ip = argv[1];
int sockfd, fd, rtrn;
char *inBuf;
struct sockaddr_in servaddr,cliaddr;
socklen_t len = sizeof(cliaddr);
/* Get Socket to Connect to Fuzz Server */
sockfd = socket(PF_INET, SOCK_STREAM, 0);
if(sockfd < 0)
{
perror("Can't Create Socket");
return -1;
}
/* Fill Out Struct */
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(BLACKBOX_PORT);
inet_pton(AF_INET, ip, &servaddr.sin_addr);
/* Attempt Connection */
fd = connect(sockfd,(struct sockaddr *)&servaddr, sizeof(servaddr));
if(fd < 0)
{
perror("Can not connect to BlackBox Fuzz server");
return -1;
}
/* Allocate Space in Memory for Incoming Connection */
inBuf = (char *) malloc(1025);
if(inBuf == NULL)
{
perror("Mem Error");
return -1;
}
/* Read From Socket */
rtrn = read(fd, inBuf, 1024);
if(rtrn < 0)
{
perror("Can't Read Data From BlackBox Server");
return -1;
}
printf("Received Data: %s\n", inBuf);
free(inBuf);
return 0;
}
Output from client:
./client 10.1.10.13
Can not connect to BlackBox Fuzz server
Connection refused
Any help would be appreciated, thanks.
Assuming that you're running this code on a little-endian machine, you need to use htons() when assigning the port number on the server side too.
(On big-endian machines htons() is a "no-op", but you should always use it to ensure portability)
Related
Re-using code here to reproduce a tcp client/server interaction.
The server initializes fine, begins listening for connections.
However, on running client ./client, the client fails with message
connect(): Cannot assign requested address
where the "failing" code from the link above (and also pasted below) is:
ret = connect(sock_fd, (struct sockaddr*)&server_addr, sizeof(server_addr));
if (ret == -1) {
perror("connect()");
close(sock_fd);
return EXIT_FAILURE;
}
When I run ifconfig, I do not see an IPv6 address. Is this a possible explanation? I am running an Ubuntu Docker image on an OSX machine.
The code is easily compilable/runnable with
gcc server.c -o server
gcc client.c -o client
./server
./client
server.c
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>
#include <netinet/in.h>
#define CLIENT_QUEUE_LEN 10
#define SERVER_PORT 7002
int main(void)
{
int listen_sock_fd = -1, client_sock_fd = -1;
struct sockaddr_in6 server_addr, client_addr;
socklen_t client_addr_len;
char str_addr[INET6_ADDRSTRLEN];
int ret, flag;
char ch;
/* Create socket for listening (client requests) */
listen_sock_fd = socket(AF_INET6, SOCK_STREAM, IPPROTO_TCP);
if(listen_sock_fd == -1) {
perror("socket()");
return EXIT_FAILURE;
}
/* Set socket to reuse address */
flag = 1;
ret = setsockopt(listen_sock_fd, SOL_SOCKET, SO_REUSEADDR, &flag, sizeof(flag));
if(ret == -1) {
perror("setsockopt()");
return EXIT_FAILURE;
}
server_addr.sin6_family = AF_INET6;
server_addr.sin6_addr = in6addr_any;
server_addr.sin6_port = htons(SERVER_PORT);
/* Bind address and socket together */
ret = bind(listen_sock_fd, (struct sockaddr*)&server_addr, sizeof(server_addr));
if(ret == -1) {
perror("bind()");
close(listen_sock_fd);
return EXIT_FAILURE;
}
/* Create listening queue (client requests) */
ret = listen(listen_sock_fd, CLIENT_QUEUE_LEN);
if (ret == -1) {
perror("listen()");
close(listen_sock_fd);
return EXIT_FAILURE;
}
client_addr_len = sizeof(client_addr);
while(1) {
/* Do TCP handshake with client */
client_sock_fd = accept(listen_sock_fd,
(struct sockaddr*)&client_addr,
&client_addr_len);
if (client_sock_fd == -1) {
perror("accept()");
close(listen_sock_fd);
return EXIT_FAILURE;
}
inet_ntop(AF_INET6, &(client_addr.sin6_addr),
str_addr, sizeof(str_addr));
printf("New connection from: %s:%d ...\n",
str_addr,
ntohs(client_addr.sin6_port));
/* Wait for data from client */
ret = read(client_sock_fd, &ch, 1);
if (ret == -1) {
perror("read()");
close(client_sock_fd);
continue;
}
/* Do very useful thing with received data :-) */
ch++;
/* Send response to client */
ret = write(client_sock_fd, &ch, 1);
if (ret == -1) {
perror("write()");
close(client_sock_fd);
continue;
}
/* Do TCP teardown */
ret = close(client_sock_fd);
if (ret == -1) {
perror("close()");
client_sock_fd = -1;
}
printf("Connection closed\n");
}
return EXIT_SUCCESS;
}
client.c
#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <unistd.h>
#define SERVER_PORT 7002
int main(int argc, char *argv[])
{
int sock_fd = -1;
struct sockaddr_in6 server_addr;
int ret;
char ch = 'a';
/* Arguments could be used in getaddrinfo() to get e.g. IP of server */
(void)argc;
(void)argv;
/* Create socket for communication with server */
sock_fd = socket(AF_INET6, SOCK_STREAM, IPPROTO_TCP);
if (sock_fd == -1) {
perror("socket()");
return EXIT_FAILURE;
}
/* Connect to server running on localhost */
server_addr.sin6_family = AF_INET6;
inet_pton(AF_INET6, "::1", &server_addr.sin6_addr);
server_addr.sin6_port = htons(SERVER_PORT);
/* Try to do TCP handshake with server */
ret = connect(sock_fd, (struct sockaddr*)&server_addr, sizeof(server_addr));
if (ret == -1) {
perror("connect()");
close(sock_fd);
return EXIT_FAILURE;
}
/* Send data to server */
ret = write(sock_fd, &ch, 1);
if (ret == -1) {
perror("write");
close(sock_fd);
return EXIT_FAILURE;
}
/* Wait for data from server */
ret = read(sock_fd, &ch, 1);
if (ret == -1) {
perror("read()");
close(sock_fd);
return EXIT_FAILURE;
}
printf("Received %c from server\n", ch);
/* DO TCP teardown */
ret = close(sock_fd);
if (ret == -1) {
perror("close()");
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
So when I ran the code on a non docker container (the host) which has an IPv6 address based on running ifconfig, I get the output
Received b from server
which appears to confirm my suspicion that the container does not support IPv6.
If anyone cares to elaborate, they are welcome to.
Your server_addr.sin6_flowspec and other members of that struct are being left uninitialized.
Start by zero'ing out your server_addr instances before passing it to connect.
Either this at declaration time:
struct sockaddr_in6 server_addr = {0};
Or a memset call to fill it with all zeros before you start assigning the members of that struct values.
memset(&server_addr, '\0', sizeof(server_addr));
I believe that will fix your issue. If not, read on.
If the above doesn't resolve your issue, it's likely because you aren't properly initializing the sin6_flowspec or other members of the sockaddr_in6 struct that aren't in the ipv4 sockaddr_in struct. You can leverage getaddrinfo to do the heavy work for you to properly fill in these fields.
int result = 0;
addrinfo* resultList = NULL;
addrinfo hints = {};
hints.ai_family = AF_INET6;
hints.ai_flags |= AI_NUMERICHOST; // comment this line out if getaddrinfo fails
hints.ai_socktype = SOCK_STREAM;
int result = getaddrinfo("::1", NULL, &hints, &resultList);
if ((result == 0) && (resultList->ai_family == AF_INET6))
{
memcpy(&server_addr, resultList->ai_addr, sizeof(sockaddr_in6));
server_addr.sin6_port = htons(SERVER_PORT);
}
else
{
// fail
}
if (resultList)
{
freeaddrinfo(&resultList);
}
resultList = NULL;
I'm implementing a simple SCTP client and server with Linux SCTP socket API. Client and server both use one-to-one socket style. After connecting to server, the client sends a hello message to server and the server responds back with its hello message. Here' the code for server and client:
server.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/sctp.h>
#include "common.h"
int main(int argc, char *argv[])
{
int srvr_sock;
struct sockaddr_in srv_addr;
struct sockaddr_in clnt_addr;
struct sctp_sndrcvinfo sndrcvinfo;
struct sctp_event_subscribe event;
socklen_t addr_sz;
char snd_buf[] = "Hello from server";
char rcv_buf[1024] = {0};
int new_fd;
int flags;
int rd_sz;
int ret;
/* One-to-one style */
/* Create socket */
srvr_sock = socket(PF_INET, SOCK_STREAM, IPPROTO_SCTP);
if (srvr_sock < 0)
{
perror("Open srvr_sock");
exit(EXIT_FAILURE);
}
/* Bind to server address */
memset(&srv_addr, 0, sizeof(srv_addr));
srv_addr.sin_family = AF_INET;
srv_addr.sin_port = htons(SERVER_PORT_NUM);
srv_addr.sin_addr.s_addr = inet_addr(SERVER_IP_ADDR_1);
ret = bind(srvr_sock, (struct sockaddr *) &srv_addr, sizeof(srv_addr));
if (ret < 0)
{
perror("Bind srvr_sock");
exit(EXIT_FAILURE);
}
/* Enable all events */
event.sctp_data_io_event = 1;
event.sctp_association_event = 1;
event.sctp_address_event = 1;
event.sctp_send_failure_event = 1;
event.sctp_peer_error_event = 1;
event.sctp_shutdown_event = 1;
event.sctp_partial_delivery_event = 1;
event.sctp_adaptation_layer_event = 1;
if (setsockopt(srvr_sock, IPPROTO_SCTP, SCTP_EVENTS, &event,
sizeof(event)) != 0)
{
perror("setsockopt failed");
exit(EXIT_FAILURE);
}
/* Listen */
ret = listen(srvr_sock, 5);
if (ret < 0)
{
perror("Listen on srvr_sock");
exit(EXIT_FAILURE);
}
/* Server loop */
while (1)
{
printf("Waiting for new connection...\n");
new_fd = accept(srvr_sock, (struct sockaddr *)&clnt_addr, &addr_sz);
if (new_fd < 0)
{
perror("Failed to accept client connection");
continue;
}
memset(rcv_buf, 0, sizeof(rcv_buf));
rd_sz = sctp_recvmsg(new_fd, (void *)rcv_buf, sizeof(rcv_buf),
(struct sockaddr *) NULL,
0,
&sndrcvinfo,
&flags);
if (rd_sz <= 0)
{
continue;
}
if (flags & MSG_NOTIFICATION)
{
printf("Notification received. rd_sz=%d\n", rd_sz);
}
printf("New client connected\n");
printf("Received %d bytes from client: %s\n", rd_sz, rcv_buf);
/* Send hello to client */
ret = sctp_sendmsg(new_fd, /* sd */
(void *) snd_buf, /* msg */
strlen(snd_buf), /* len */
NULL, /* to */
0, /* to len */
0, /* ppid */
0, /* flags */
STREAM_ID_1, /* stream_no */
0, /* TTL */
0 /* context */);
if (ret < 0)
{
perror("Error when send data to client");
}
else
{
printf("Send %d bytes to client\n", ret);
}
if (close(new_fd) < 0)
{
perror("Close socket failed");
}
}
close(srvr_sock);
return 0;
}
client.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/sctp.h>
#include "common.h"
int main(int argc, char *argv[])
{
int conn_fd;
struct sockaddr_in srvr_addr;
struct sctp_sndrcvinfo sndrcvinfo;
socklen_t addr_sz = sizeof(struct sockaddr_in);
int flags;
char rcv_buf[1024] = {0};
char snd_buf[] = "Hello from client";
int rcv_cnt;
int ret;
/* One-to-one style */
/* Create socket */
conn_fd = socket(PF_INET, SOCK_STREAM, IPPROTO_SCTP);
if (conn_fd < 0)
{
perror("Create socket conn_fd");
exit(EXIT_FAILURE);
}
/* Specify the peer endpoint to which we'll connect */
memset(&srvr_addr, 0, sizeof(srvr_addr));
srvr_addr.sin_family = AF_INET;
srvr_addr.sin_port = htons(SERVER_PORT_NUM);
srvr_addr.sin_addr.s_addr = inet_addr(SERVER_IP_ADDR_1);
/* Connect */
ret = connect(conn_fd, (struct sockaddr *)&srvr_addr, sizeof(srvr_addr));
if (ret < 0)
{
perror("Connect failed");
exit(EXIT_FAILURE);
}
printf("Connected to server\n");
/* Send hello to server */
ret = sctp_sendmsg(conn_fd, (void *)snd_buf, strlen(snd_buf),
(struct sockaddr *) &srvr_addr, sizeof(srvr_addr), 0,
0, STREAM_ID_1, 0, 0);
if (ret < 0)
{
perror("Send to server failed");
close(conn_fd);
exit(EXIT_FAILURE);
}
else
{
printf("Send %d bytes to server\n", ret);
}
/* Read message from server */
rcv_cnt = sctp_recvmsg(conn_fd, (void *)rcv_buf, sizeof(rcv_buf),
(struct sockaddr *) &srvr_addr, &addr_sz,
&sndrcvinfo, &flags);
if (rcv_cnt <= 0)
{
printf("Socket error or EOF\n");
}
else if (flags & MSG_NOTIFICATION)
{
printf("Notification received. rcv_cnt=%d\n", rcv_cnt);
}
else
{
printf("Received %d bytes from server: %s\n", rcv_cnt, rcv_buf);
}
/* close socket */
close(conn_fd);
return 0;
}
common.h
#define SERVER_PORT_NUM 16789
#define SERVER_IP_ADDR_1 "192.168.56.102"
#define STREAM_ID_1 1
Client and server are running on 2 Debian VMs in the same subnet, client's IP is 192.168.56.101, server's IP is 192.168.56.102.
When I start the server and then run the client, most of the time the client fails with following output:
./client
Connected to server
Send to server failed: Cannot assign requested address
However the server shows that it has read data sent from client and has responded with server hello message:
./server
Waiting for new connection...
Notification received. rd_sz=20
New client connected
Received 20 bytes from client: ▒
Send 17 bytes to client
Waiting for new connection...
Also the data received from client is corrupted in this case.
I tried to run the client many times and sometimes it succeeds:
$ ./client
Connected to server
Send 17 bytes to server
Received 17 bytes from server: Hello from server
The server still shows same log messages in this case.
Why would the client fail most of the time while only succeed a few times? The result seems to be unpredictable to me. Also why the data read by server is corrupted in server's output?
Try to bind also client socket.
In client.c between socket create and before connect put:
cli_addr.sin_family = AF_INET;
cli_addr.sin_port = 0;
cli_addr.sin_addr.s_addr = inet_addr(INADDR_ANY); /* or inet_addr("192.168.56.101");
for multiple ip addresses or network cards */
ret = bind(conn_fd, (struct sockaddr *) &cli_addr, sizeof(cli_addr));
if (ret < 0)
{
perror("Bind client_sock");
exit(EXIT_FAILURE);
}
I wrote a simple TCP echo server to handle multiple clients. It uses select() to get multiple connections.
Server Code:
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <string.h>
int create_listener(uint16_t port) {
int listen_fd;
struct sockaddr_in name;
listen_fd = socket(AF_INET, SOCK_STREAM, 0);
if (listen_fd < 0) {
perror ("socket");
exit(EXIT_FAILURE);
}
bzero(&name, sizeof(name));
name.sin_family = AF_INET;
name.sin_addr.s_addr = htonl(INADDR_ANY);
name.sin_port = htons(port);
if (bind(listen_fd, (struct sockaddr *) &name, sizeof(name)) < 0) {
perror ("bind");
exit(EXIT_FAILURE);
}
return listen_fd;
}
int read_from_client(int fd) {
char buffer[100];
int nbytes;
nbytes = read(fd, buffer, 100);
if (nbytes < 0) {
perror("read");
exit(EXIT_FAILURE);
}
else if (nbytes == 0) {
return -1;
}
else {
fprintf(stderr, "Server: got message: %s\n", buffer);
write(fd, buffer, strlen(buffer) + 1);
return 0;
}
}
int main(int argc, char *argv[]) {
int listen_fd;
uint16_t port = 22000;
fd_set active_fd_set, read_fd_set;
int i;
struct sockaddr_in servaddr;
/* Create the socket and set it up to accept connections. */
listen_fd = create_listener(port);
if (listen(listen_fd, 10) < 0) {
perror("listen");
exit(EXIT_FAILURE);
}
/* Initialize the set of active sockets. */
FD_ZERO(&active_fd_set);
FD_SET(listen_fd, &active_fd_set);
while (1) {
/* Block until input arrives on one or more active sockets. */
read_fd_set = active_fd_set;
if (select(FD_SETSIZE, &read_fd_set, NULL, NULL, 0) < 0) {
perror("select");
exit(EXIT_FAILURE);
}
/* Service all the sockets with input pending. */
for (i = 0; i < FD_SETSIZE; ++i) {
if (FD_ISSET(i, &read_fd_set)) {
if (i == listen_fd) {
/* Connection request on original socket. */
int new_fd;
new_fd = accept(listen_fd, (struct sockaddr *) NULL, NULL);
if (new_fd < 0) {
perror ("accept");
exit(EXIT_FAILURE);
}
FD_SET(new_fd, &active_fd_set);
}
else {
/* Data arriving on an already-connected socket. */
if (read_from_client(i) < 0) {
close(i);
FD_CLR(i, &active_fd_set);
}
}
}
}
}
return 0;
}
Client code:
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[]) {
int sockfd, n;
char sendline[100];
char recvline[100];
struct sockaddr_in servaddr;
sockfd = socket(AF_INET, SOCK_STREAM, 0);
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(22000);
inet_pton(AF_INET, "127.0.0.1", &(servaddr.sin_addr));
connect(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr));
while (1) {
bzero(sendline, 100);
bzero(recvline, 100);
fgets(sendline, 100, stdin);
write(sockfd, sendline, strlen(sendline) + 1);
read(sockfd, recvline, 100);
printf("%s", recvline);
}
return 0;
}
The problem is when I run server in one terminal and run two clients in another two terminals. If I use Ctrl+C to terminate one client, the server automatically terminates. I'm wondering why the server acts this way. What I'm expecting is the server runs forever. When client 1 terminates, server should still has a live connection with client 2.
Looks like you're hitting the exit in read_from_client. In general, in a server that serves multiple clients, you probably don't want to exit when you have a failure with one of the client connections.
I've been scratching my head with this one for quite a while now. I've got a simple client and server program and I want the server to echo what the client sends it. I can't figure out why the server isn't receiving any data.
Client code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#define MAX_BUF 64
#define MAX_ARGS 8
void initClient(int*);
int main()
{
int socket;
/* initialize socket and connect to server */
initClient(&socket);
while(1){
char in[80];
char temp[80];
bzero(in, 80);
bzero(temp, 80);
printf("What's your message: ");
gets(in);
strcpy(temp, in);
send(socket, temp, strlen(temp), 0);
if(strcmp(temp, "exit") == 0)
break;
}
return 0;
}
void initClient(int *sock)
{
FILE *configFile;
char ip[MAX_BUF];
int port;
int i;
struct sockaddr_in addr;
/* get IP address and port number from config file */
if (!(configFile=fopen(".config","r"))) {
printf("cannot read config file...\n");
exit(1);
}
fscanf(configFile, "%s", ip);
fscanf(configFile, "%d", &port);
fclose(configFile);
/* create socket and connect to logger */
sock = (int *)socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
if(sock < 0){
printf("Could not open socket\n");
exit(-1);
}
/* setup address */
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = inet_addr(ip);
addr.sin_port = htons((unsigned short) port);
/* connect to server */
i = connect((int)sock,
(struct sockaddr *) &addr,
sizeof(addr));
if (i<0) {
printf("client could not connect!\n");
exit(-1);
}
}
Server code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include <time.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#define MAX_BUF 64
int main()
{
FILE *configFile;
char ip[MAX_BUF];
int port;
char str[MAX_BUF];
/* get IP address and port number from config file */
if (!(configFile=fopen(".config","r"))) {
printf("cannot read config file...\n");
exit(1);
}
fscanf(configFile, "%s", ip);
fscanf(configFile, "%d", &port);
fclose(configFile);
int myListenSocket, clientSocket;
struct sockaddr_in myAddr, clientAddr;
int i, addrSize, bytesRcv;
/* Create socket */
myListenSocket = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
if(myListenSocket < 0) {
printf("Couldn't open socket\n");
exit(-1);
}
/* Set up server address */
memset(&myAddr, 0, sizeof(myAddr));
myAddr.sin_family = AF_INET;
myAddr.sin_addr.s_addr = htonl(INADDR_ANY);
myAddr.sin_port = htons((unsigned short) port);
/* Binding */
i = bind(myListenSocket, (struct sockaddr *) &myAddr, sizeof(myAddr));
if(i < 0){
printf("Couldn't bind socket\n");
exit(-1);
}
/* Listen */
i = listen(myListenSocket, 5);
if(i < 0){
printf("Couldn't listen\n");
exit(-1);
}
/* Wait for connection request */
addrSize = sizeof(clientAddr);
clientSocket = accept(myListenSocket,
(struct sockaddr *) &clientAddr,
&addrSize);
if(clientSocket < 0){
printf("Couldn't accept the connection\n");
exit(-1);
}
/* Read message from client and do something with it */
char buffer[100];
while(1){
bzero(buffer, 100);
bytesRcv = read(clientSocket, buffer, sizeof(buffer));
buffer[bytesRcv] = 0;
printf("this is what the client sent: %s\n", buffer);
if(bytesRcv == 0){
break;
}
}
close(myListenSocket);
close(clientSocket);
return 0;
}
When you pass a pointer you should reference it as *sock to get its value, otherwise if you reference it as sock you are, in fact, getting the address and not the value of the variable.
Here is your initClient function corrected:
void initClient(int *sock)
{
FILE *configFile;
char ip[128];
int port;
int i;
struct sockaddr_in addr;
/* get IP address and port number from config file */
if (!(configFile=fopen(".config","r"))) {
printf("cannot read config file...\n");
exit(1);
}
fscanf(configFile, "%s", ip);
fscanf(configFile, "%d", &port);
fclose(configFile);
/* create socket and connect to logger */
*sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
if(*sock < 0){
printf("Could not open socket\n");
exit(-1);
}
/* setup address */
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = inet_addr(ip);
addr.sin_port = htons((unsigned short) port);
/* connect to server */
i = connect(*sock, (struct sockaddr *) &addr, sizeof(addr));
if (i<0) {
printf("client could not connect!\n");
exit(-1);
}
}
While trying to implement a server and client, I noticed that the client was writing to stdout instead
of through the network. I figured out that the file descriptor being returned by connect() is always zero, which explains why it was writing to stdout. But I can not figure out why connect() always returns zero instead of a valid socket. All the articles on the web I found with the same problem were due to precedence issues with wrapping if() around the connect() call. But I haven't done that, any help would be appreciated.
server code
int setUpServer(struct fuzzerObj *ptr, int *firstClient)
{
/* Declarations */
int hostSocket, yes = 1, rtrn, clientfd;
union
{
struct sockaddr_in in;
}address;
/* Create Socket */
hostSocket = socket(AF_INET, SOCK_STREAM, 0);
if(hostSocket < 0)
{
errorHandler("Could not create socket\n", FUNCTION_ID_SET_UP_SERVER);
return -1;
}
/* Reuse Address */
rtrn = setsockopt(hostSocket, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
if(rtrn < 0)
{
errorHandler("Couldn't Reuse Address\n", FUNCTION_ID_SET_UP_SERVER);
return -1;
}
/* Set Up Struct */
address.in.sin_len = sizeof(address.in);
address.in.sin_family = AF_INET;
address.in.sin_port = htons(BBPORT_NUMBER);
address.in.sin_addr.s_addr = htonl(INADDR_ANY);
memset(address.in.sin_zero, 0, sizeof(address.in.sin_zero));
/* Bind Address to Socket */
rtrn = bind(hostSocket, (struct sockaddr*) &address, address.in.sin_len);
if(rtrn < 0)
{
errorHandler("Can't Bind Address to Socket\n", FUNCTION_ID_SET_UP_SERVER);
return -1;
}
/* listen */
rtrn = listen(hostSocket, ptr->numberOfClients);
if(rtrn < 0)
{
errorHandler("Can't Listen\n", FUNCTION_ID_SET_UP_SERVER);
return -1;
}
while(1)
{
rtrn = acceptClient(hostSocket, &clientfd);
if(rtrn < 0)
{
printf("Can't Accept Client\n");
return -1;
}
break;
}
*firstClient = clientfd;
return 0;
}
client code
#include <CoreFoundation/CoreFoundation.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <netinet/in.h>
#include <stdbool.h>
#include <sys/types.h>
#include <unistd.h>
#include <errno.h>
#define BLACKBOX_PORT 9696
int main(int argc, char *argv[])
{
/* Check To See If an argument was passed */
if(argc < 2)
{
printf("No enough Arguments\n");
return -1;
}
/* Declaration's */
const char *ip = argv[1];
int sockfd, fd, rtrn;
char *outBuf;
struct sockaddr_in servaddr;
/* Get Socket to Connect to Fuzz Server */
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if(sockfd < 0)
{
perror("Can't Create Socket");
return -1;
}
/* Fill Out Struct */
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(BLACKBOX_PORT);
inet_pton(AF_INET, ip, &servaddr.sin_addr);
/* Attempt Connection */
fd = connect(sockfd,(struct sockaddr *)&servaddr, sizeof(servaddr));
if(fd < 0)
{
perror("Can not connect to BlackBox Fuzz server");
return -1;
}
/* Allocate Space in Memory for Outgoing Connection */
rtrn = asprintf(&outBuf, "Mac OSX 10.9\n");
if(rtrn < 0)
{
perror("Copy Error");
return -1;
}
/* Send Data to Fuzzer via Socket */
rtrn = send(fd, outBuf, strlen(outBuf), 0);
if(rtrn < 0)
{
perror("Can't write Data to BlackBox Server");
return -1;
}
free(outBuf);
return 0;
}
Upon successfully calling connect(), the sockfd is connected. The 0 return value indicates that the call is successful. If the value was not 0, it would have indicated an error, and that the connection attempt has failed or is not yet completed (if the connect is non-blocking).
After determining that connect() has succeeded, call send() on the sockfd, not on the return value of the connect() call.
rtrn = send(sockfd, outBuf, strlen(outBuf), 0);