Check whenever server comes online using UDP in C programming in client - c

i have written a normal udp client server programm in C programming to send data from client to server and recieve an acknowledgment from it for the message been sent..
so my question is that incase if my server is down and my client sends a message to server ..
how can my client sense whether the server is up or down(nt working).
all sugesstions are welcomed .. and didnot find nythin related to sensing a server.. so please help me on this
the code for client is here
#include<netinet/in.h>
#include <sys/types.h>
#include <sys/socket.h>
#include<stdio.h>
#include <arpa/inet.h>
#include <string.h>
#include<fcntl.h>
#include<unistd.h>
#include<stdlib.h>
#include<sqlite3.h>
void enterdb(char *);
int main()
{
int sfd,l;
char *buf=(char*)malloc(100*sizeof(char)),buf1[10]="";//=(char *)malloc(100*sizeof(char));
struct sockaddr_in server,client;
sfd=socket(AF_INET,SOCK_DGRAM,0);
int sender_len=sizeof(server);
struct msghdr msg;
struct iovec iov;
bzero(&server,sizeof(server));
server.sin_family=AF_INET;
server.sin_port=htons(1300);
server.sin_addr.s_addr=inet_addr("127.0.0.1");
msg.msg_name = &server;
msg.msg_namelen = sender_len;
msg.msg_iov = &iov;
msg.msg_iovlen = sizeof(buf1);
msg.msg_iov->iov_base = buf1;
msg.msg_iov->iov_len = 9;
msg.msg_control = 0;
msg.msg_controllen = 0;
msg.msg_flags = 0;
printf("Enter the message:");
gets(buf);
char *test="quit";
if(strcmp(test,buf)==0)
{
printf("now exiting\n");
close(sfd);
exit(0);
return 0;
}
else
{
int s;
s=sendto(sfd,buf,strlen(buf),0,(struct sockaddr *)&server,sizeof(server));
printf("control passed on here and message sent is of %d bytes \n",s);
printf("control passed on here again and message sent is of %d bytes\n ",s);
//sleep(5);
int length = sizeof(server);
printf("%s\n",buf1);
int x = recvmsg(sfd,&msg,MSG_DONTWAIT);
if(x<0)
{
printf("error");
}
/*while( ( x =recvfrom(sfd,buf1,100,0,(struct sockaddr*)&server,&length)))
{
if(x<0)
return 1;
break;
}*/
else {
printf("%s\n",buf1);
char *recv="recieved";
if(strcmp(recv,buf1) != 0 )
{
printf("**** control is in connect ***\n");
enterdb(buf);
}
else
{
memset(buf,0,strlen(buf));
printf("MESSAGE FOR SERVER : you sent me the message has been- %s\n",buf1);
}
}
}
close(sfd);
return 0;
}

The usual way of detecting whether a server is down is by sending it a message and waiting for the answer for a limited time (maybe 30s, maybe 15 min, depending on the application and the network...). In your case, you'd have to setup a time-out in your client, which you would start on sending a message and stop when receiving the acknowledgment. If the time-out is not stopped before it "wakes up", then it triggers an exception or sets a specific variable (these are usual ways of informing the application that the time-out has elapsed without an answer from the server).

Related

How to establish a continuous Bluetooth connection with BlueZ so I can transfer to and receive data from an Arduino?

I've been making a map making robot car with Arduino for class. I want to make a user interface for it in C (on a PC running Linux) that would work like this: the user can press a Start and a Stop button, or click a specific area of the map to send the robot to there. Right now my test setup code looks like this:
Arduino:
`
if (BTSerial.available() > 0) {
c = BTSerial.readStringUntil('\n').toInt();
BTSerial.write(c);
if(c == 8) {
Buzzing(SOS);
BTSerial.println("eight");
}
}
**PC program**:
#include <stdio.h>
#include <unistd.h>
#include <sys/socket.h>
#include <bluetooth/bluetooth.h>
#include <bluetooth/rfcomm.h>
int main(int argc, char **argv)
{
struct sockaddr_rc addr = { 0 };
int s, status;
char dest[18] = "98:DA:60:03:F2:92";
// allocate a socket
s = socket(AF_BLUETOOTH, SOCK_STREAM, BTPROTO_RFCOMM);
// set the connection parameters (who to connect to)
addr.rc_family = AF_BLUETOOTH;
addr.rc_channel = (uint8_t) 1;
str2ba( dest, &addr.rc_bdaddr );
// connect to server
status = connect(s, (struct sockaddr *)&addr, sizeof(addr));
// send a message
if( status == 0 ) {
status = write(s, "8", 2);
}
if( status < 0 ) perror("uh oh");
int client, bytes_read;
char buf[1024] = { 0 };
// put socket into listening mode
listen(s, 1);
// read data from the client
bytes_read = read(client, buf, sizeof(buf));
if( bytes_read > 0 ) {
printf("received [%s]\n", buf);
}
close(s);
return 0;
}
`
Ideally if I send the number 8 to the Arduino it would send back the string "eight". When I run my PC program, my PC connects to the Arduino (I get a notification from the OS that my PC is connected and also the led on my HC-06 Bluetooth module connected to the Arduino stops blinking signaling that a device was connected to it) and the buzzer connected to the Arduino starts buzzing the morse code of SOS as expected. However after a second my program terminates, the Bluetooth connection ends (I get a notification that my PC is disconnected and the led on the Bluetooth module starts blinking again) and I don't get back the expected "eight" string.
I'm still just a beginner when it comes to the C language and since I can not find a detailed documentation of BlueZ, I'm kind of stuck. Any help would be greatly appreciated!
I tried to combine the server and the client code from this site: https://people.csail.mit.edu/albert/bluez-intro/x502.html#rfcomm-server.c
I also tested my code on the Arduino using Putty on PC and it worked with it properly.
Calling listen on the socket doesn't do what you think it does. Listening does not mean "wait for data". It means "wait for connect". And you cannot read from the listening socket; you can only accept the connection.
Your socket is already connected. Don't listen. Just read.
So after a bit of work I finally could get it working. I only needed to change the first parameter of the read() function. Here's my final code:
#include <stdio.h>
#include <unistd.h>
#include <sys/socket.h>
#include <bluetooth/bluetooth.h>
#include <bluetooth/rfcomm.h>
int main(int argc, char **argv)
{
struct sockaddr_rc addr = { 0 }, rem_addr = { 0 };
int s, status;
char dest[18] = "98:DA:60:03:F2:92";
// allocate a socket
s = socket(AF_BLUETOOTH, SOCK_STREAM, BTPROTO_RFCOMM);
// set the connection parameters (who to connect to)
addr.rc_family = AF_BLUETOOTH;
addr.rc_channel = (uint8_t) 1;
str2ba( dest, &addr.rc_bdaddr );
// connect to server
status = connect(s, (struct sockaddr *)&addr, sizeof(addr));
// send a message
if( status == 0 ) {
status = write(s, "8", 2);
}
if( status < 0 ) perror("uh oh");
int bytes_read;
char buf[1024] = { 0 };
// read data from the client
bytes_read = read(s, buf, sizeof(buf));
if( bytes_read > 0 ) {
printf("%s", buf);
}
close(s);
return 0;
}
This code sends the number "8" to the Arduino, to which the Arduino replies with the string "eight". It's probably not the nicest C code for Bluetooth connection, but at least it's working I guess.

IRC bot malfunction

I have attempted to make a IRC bot in C. When the bot attempts to connect to an IRC server it enters an infinite loop where it receives nothing.
I am not sure if this is because my process to join the IRC server is malformed or if I am missing some data that should be sent/received.
#include<stdio.h>
#include<sys/socket.h>
#include<netdb.h>
#include<string.h>
#include<stdlib.h>
#include<time.h>
#define MAXSIZE 4096
void delay(int milliseconds)
{
long pause;
clock_t now;
pause = milliseconds*(CLOCKS_PER_SEC/1000);//set delay using
now = clock();
while( now < pause )
now = clock();
}
int send_data(int sockfd, char message[])
{
send(sockfd, message, strlen(message), 0);
printf("OUT: %s\n", message);
return 1;
}
int recv_data(int sockfd, char *message)
{
int n;
n = recv(sockfd, message, MAXSIZE, 0);
printf("IN: %s\n", message);
return n;
}
int tcp_connect(int *sockfd, char server[], char port[])
{
//declare variables
struct addrinfo hints, *res;
//zero out structures
memset(&hints,0,sizeof(hints));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
//query DNS server for IP address and port
getaddrinfo(server,port,&hints,&res);
//create socket for data transmission
*sockfd = socket(res->ai_family,res->ai_socktype,0);
if (*sockfd < 0)
{
printf("failure to create socket\n");
return 0;
}
//connect to server side port using created socket
if (connect(*sockfd, res->ai_addr, res->ai_addrlen)!= 0)
{
printf("failure to connect to port\n");
return 0;
}
freeaddrinfo(res);
return 1;
}
int irc_auth(int sockfd)
{
//create and start clock
clock_t start_t;
start_t = clock();
//seed RNG with clock output
srand(start_t);
//generate necessary variables
char name[15] = "bot";
char user[35] = "USER ";
char nick[20] = "NICK ";
char join[20] = "JOIN #randChat\r\n";
int i,id;
//generate random character for ID tag A-Z
for(i=0; i<5; i++)
{
id = rand() % 91;
if(id < 65)
{
while(id < 65)
{
id = rand() % 91;
}
}
name[strlen(name)] = id;
}
//append return and null to string
strcat(nick,name);
strcat(nick,"\r\n");
//append to finish creating USER IRC command
strcat(user,name);
strcat(user," 8 * :");
strcat(user,name);
strcat(user,"\r\n");
//send data to server
send_data(sockfd,user);
delay(1000);
send_data(sockfd,nick);
delay(1000);
send_data(sockfd,join);
return 1;
}
int main (int argc, char *argv)
{
//variables
int sockfd, n, flag;
char *mesg_in = malloc(sizeof(char) * MAXSIZE);
char *pos;
char nick[30];
char *mesg_out = malloc(sizeof(char) * MAXSIZE);
//connect to port 6667 of irc.freenode.org using tcp
while(flag<1)
{
if(tcp_connect(&sockfd,"irc.freenode.org","6667") == 1)
{
flag = 1;
}
}
//IRC channel authentication
irc_auth(sockfd);
//command loop
while(1)
{
mesg_in[0] = 0;// zero out message
//memset(mesg_in,0,strlen(mesg_in));
n = recv_data(sockfd,mesg_in);// pull message from channel
if (n > 0)// check to see if it recieved a command
{
mesg_in[n] = 0;// set null at the end of recieved data
//respond to ping commands from server
if(strstr(mesg_in,"PING") != NULL)
{
mesg_out[0] = 0;// zero out message
pos = strstr(mesg_in," ")+1;// point to data needed
//append to out bound message
sprintf(mesg_out,"PONG %s\r\n",pos);
//send outbound message
send_data(sockfd,mesg_out);
}
}
}
}
any and all help would be greatly appreciated
Whatever other problems there might be, delay() is one. Your function in this test program, waits two seconds and then prints 1 2 3 all at the same time, because it only considers elapsed time from the program start, and not from the current moment.
#include <stdio.h>
#include <time.h>
void delay(int milliseconds)
{
long pause;
clock_t now;
pause = milliseconds*(CLOCKS_PER_SEC/1000);//set delay using
now = clock();
while( now < pause )
now = clock();
}
int main (void)
{
delay(2000);
printf("1\n");
delay(2000);
printf("2\n");
delay(2000);
printf("3\n");
return 0;
}
This version prints 1 2 3 at two second intervals
#include <stdio.h>
#include <time.h>
void delay(clock_t milliseconds)
{
clock_t elapsed, pause, stamp;
stamp = clock();
pause = milliseconds * CLOCKS_PER_SEC / 1000;
while ((elapsed = clock() - stamp) < pause);
}
int main (void)
{
delay(2000);
printf("1\n");
delay(2000);
printf("2\n");
delay(2000);
printf("3\n");
return 0;
}
Please also notice, that in integer arithmetic, I do the multiplication before the division.
Rethink your client and make it a state machine instead driven by an event engine such as epoll(), kqueue(), select() or poll().
Generally, an IRC command generates a reply, but you don't know when they are going to arrive, and the protocol is designed such that you might want to send commands that aren't initiated by data coming from the server.
Using a delay to authenticate to an IRC server is a no-no because there are various other commands that can be generated as part of authentication such as PING or CTCP's etc, your nick being in use, etc.
Also, according to the RFC the NICK command must come first before user. Generally, IRC servers are forgiving, but don't take this for granted. As the adage goes, "be generous in what you accept and strict in what you send".

The code is compiled successfully but the func() is not being executed. Someone please suggest required changes

//SERVER SIDE SCRIPT for Diffie-Hellman using sockets.
#include<stdio.h>
#include<netinet/in.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netdb.h>
#include<string.h>
#include<math.h>
#include<stdlib.h>
#define MAX 80
#define PORT 43461
#define SA struct sockaddr
char* itoa(int value, char* str, int radix) {
static char dig[] =
"0123456789"
"abcdefghijklmnopqrstuvwxyz";
int n = 0, neg = 0;
unsigned int v;
char* p, *q;
char c;
if (radix == 10 && value < 0) {
value = -value;
neg = 1;
}
v = value;
do {
str[n++] = dig[v%radix];
v /= radix;
} while (v);
if (neg)
str[n++] = '-';
str[n] = '\0';
for (p = str, q = p + (n-1); p < q; ++p, --q)
c = *p, *p = *q, *q = c;
return str;
}
void func(int sockfd)
{
printf("hello"); //This statement is not being displayed and rest of the code not executed
char buff[MAX],uname[MAX],pass[MAX];
int n,clen,a1,a2,b2,val,key;
struct sockaddr_in cli;
clen=sizeof(cli);
xx:
//RECIEVING USERNAME
bzero(uname,MAX);
recvfrom(sockfd,uname,sizeof(buff),0,(SA *)&cli,&clen);
printf("Username received");
//RECEIVING PASSWORD
bzero(pass,MAX);
recvfrom(sockfd,pass,sizeof(buff),0,(SA *)&cli,&clen);
if(strcmp(uname,"admin") == 10 && strcmp(pass,"admin") == 10)
{
printf("Accepted");
//RECEIVING NUMBER FROM CLIENT
recvfrom(sockfd,buff,sizeof(buff),0,(SA *)&cli,&clen);
b2=atoi(buff);
printf("Received from client\n");
//GENERATING SERVER SIDE NUMBER
a1=(rand() % 19) + 1; // Random value selected by Server
a2=pow(7,a1);
a2=a2 % 11; // Server Generating value to be sent G:7 , P:11
//Sending the value-a2
bzero(uname,MAX);
itoa(a2,buff,10);
sendto(sockfd,buff,sizeof(buff),0,(SA *)&cli,clen);
printf("Server side number sent\n");
//GENERATING KEY AND THE DATA
key=pow(b2,a1);
key=key % 11; // G:7 , P:11
val=key*1024; // DATA: 7060
//Sending the data required
bzero(uname,MAX);
itoa(a1,buff,10);
sendto(sockfd,buff,sizeof(buff),0,(SA *)&cli,clen);
printf("Data sent \n");
}
else
{
printf("Incorrect Username-Password combination. Waiting for next try \n");
strcpy(buff,"wrong");
sendto(sockfd,buff,sizeof(buff),0,(SA *)&cli,clen);
goto xx;
}
}
int main()
{
int sockfd;
struct sockaddr_in servaddr;
sockfd=socket(AF_INET,SOCK_DGRAM,0);
if(sockfd==-1)
{
printf("socket creation failed...\n");
exit(0);
}
else
printf("Socket successfully created..\n");
bzero(&servaddr,sizeof(servaddr));
servaddr.sin_family=AF_INET;
servaddr.sin_addr.s_addr=htonl(INADDR_ANY);
servaddr.sin_port=htons(PORT);
if((bind(sockfd,(SA *)&servaddr,sizeof(servaddr)))!=0)
{
printf("socket bind failed...\n");
exit(0);
}
else
{
printf("%d",sockfd);// This value is displayed in the output screen
printf("Socket successfully binded..\n");}
func(sockfd);
close(sockfd);
}
When the script is executed, The binding is done successfully and the same message is displayed on the output screen. But the function call for func() is not executed.I do not get the first statement of the function call-'Hello' in the execution.Please suggest the changes required in this code.
If bind() was successful then the func() will be called. The reason why you are not seeing your output is because stdout is usually buffered and it will flush it once the internal buffer is full.
Add \n to your debug printf() calls which will force it to flush the output.
printf("hello\n");
Similarly, other debug printf's. You could also use fflush(stdout); to flush stdout.
Obviously, you need to client code as server is waiting for it in your code.

Why i am not able to read multiple strings in the server file?

While working in client-server programming, I have passed 3 strings in client, which will be received by server and it should be printed in there 3 times. (i.e I have used a 'for' loop which will do the read & write operations in client & server side respectively.), but in server only the 1st string is getting printed.
Please explain,
Here is my code
server.c
#include "head.h"
void readstr(int connfd ,char [][20]);
//void writestr(char * ,int);
int main(int c ,char *v[])
{
int sd,connfd,retbind;
struct sockaddr_in serveraddress ,cliaddr;
socklen_t len;
char buf[100] ,databuf[1024][4];
sd =socket( AF_INET ,SOCK_STREAM ,0);
if (sd<0)
{
exit(1);
}
memset(&serveraddress ,0 ,sizeof(serveraddress));
serveraddress.sin_family =AF_INET;
serveraddress.sin_port =htons(MYPORT);
serveraddress.sin_addr.s_addr =htonl(INADDR_ANY);
retbind =bind(sd ,(struct sockaddr*)&serveraddress ,sizeof(serveraddress
));
if(-1 ==retbind)
{
perror("bind fails ");
exit(0);
}
listen(sd ,4);
for(;;)
{
printf("i am waiting for client\n");
len =sizeof(cliaddr);
connfd = accept(sd ,(struct sockaddr*)&cliaddr ,&len);
if(connfd <0)
{
if(errno ==EINTR)
printf("interrupt");
continue;
}
printf("connection from %s\n",inet_ntop(AF_INET ,&cliaddr.sin_addr,buf ,
sizeof(buf)));
readstr(connfd ,databuf);
close(connfd);
printf("\n fini one clieni");
}
return 0;
}
void readstr(int connfd ,char str[3] [20])
{
int pointer=0 ,i=0, n,pos=0;
memset(str ,'\0',sizeof(str));
printf("\n->Connfd : %d\n",connfd);
printf("\n----->String recieved : %s\n",str);
for(i=0;i<3;i++)
{
while((n=read(connfd ,str[i] ,20)) >>0)
{
printf("Looping while\n");
pos =pos +n;
}
str[i][pos] ='\0';
}
for(i=0;i<3;i++)
{
printf("\n%s",str[i]);
}
}
client.c
#include "head.h"
void send1(int ,char*);
int main(int c,char*v[])
{
int sd,i;
int len;
char buf[20][4];
struct sockaddr_in serveraddress;
sd = socket(AF_INET ,SOCK_STREAM ,0);
if (sd<0)
perror("socket");
memset(&serveraddress ,0 ,sizeof(serveraddress));
serveraddress.sin_family =AF_INET;
serveraddress.sin_port =htons(atoi(v[1]));
serveraddress.sin_addr.s_addr =inet_addr(v[2]);
if(connect(sd,(struct sockaddr*)&serveraddress ,sizeof(serveraddress)) <
0)
{
printf("cannot connect to server");
exit(1);
}
for(i=0;i<3;i++)
{
memset(buf ,'\0',sizeof(buf));
printf("\n string");
fgets(buf[i],20,stdin);
len =strlen(buf[i]);
if(buf[i][len] =='\n')
buf[i][len]='\0';
// scanf("%s",buf[i]);
send1(sd ,(char *)buf);
}
shutdown(sd ,SHUT_WR);
}
void send1(int sd ,char *str)
{
int n ,byteswritten =0, wr;
char buf[1024];
strcpy(buf ,str);
n =strlen(buf);
while(byteswritten < n)
{
printf("\nStart writing in client side\n");
wr = write(sd , buf+byteswritten ,(n-byteswritten));
byteswritten+=wr;
}
printf("\n string sent %s" ,buf);
}
In client.c main:
char buf[20][4];
change to:
char buf[4][20];
In server.c readstr:
while((n=read(connfd ,str[i] ,20)) >>0)
change to:
while((n = read(connfd, &str[i][pos], 20)) > 0)
pos needs to be reset to 0 inside the for loop.
Also, the client reads 3 strings of up to 20 chars each from stdin and writes them to the socket.
The server expects 3 strings of exactly 20 chars each.
You should either use some kind of record separator, like \n, in your network protocol, or use fixed length, i.e. pad the input strings to 20 characters.
There may be more errors in your code, I stopped looking after finding these.
It has been over 1 hour on SO and you haven't got an answer.. to what seems like a very simple problem(odd feat). you know why?
because its very painful to go through your code.
document it!
divide it into modules - init_net(), form_pkt(),
send_pkt(), exit(),.. etc
describe your problem properly.
how many client are you running?
what happens after only first strings get printed. does you code stops, loops forever what?
have you looked through a packet capture tool like tcpdump, wireshark, etc
and before I get to the main problem.. I see things like "databuf[1024][4]" being passed to a function readstr() with formal arguments "char str[3] [20]".
couple of advice
run your code through a static tool analyzer to look for basic warnings.
strings are not a great idea to send on network, learn how to define a packet structure with header and data part, etc
also I believe you are looking for a Packet like communication instead of stream based. understand the difference!
I do not know the answer to that question unless you present it properly. this time and every next time.

g_io_channel + socket = server , still didnt receive proper data and just get one client ? in C language

folks,
if you dont mind please see following code :
#include <glib.h>
#include <gio/gio.h> // gio channel
#include <sys/socket.h> //socket();
#include <netdb.h> // structure
#include <stdio.h> // printf
void deal(GIOChannel *in, GIOCondition condition, gpointer data)
{
struct sockaddr_storage income;
int insock = g_io_channel_unix_get_fd(in);
socklen_t income_len = sizeof(income);
int newsock = accept(insock, (struct sockaddr*)&income, &income_len );
if(newsock == -1)
{
printf("failure on newsock\n");
}
char buff[128];
int recv_total = 0;
int recv_byte = 128;
int recv_sizing;
while (recv_total < recv_byte ){
recv_sizing = recv(newsock,buff + recv_total,recv_byte,0);
// breaking if recv_sizing = -1 assuming as error, 0 assuming as lost communication from client suddenly
if(recv_sizing < 0 || recv_sizing == 0)
{
printf("connection lost or error while recv(); [ just guess ] number : %d \n",recv_sizing);
break;
}
recv_byte -= recv_sizing;
recv_total += recv_sizing;
}
buff[recv_total] = '\0';
//recv_sizing = recv(newsock,buff,recv_byte,0);
printf("data : %s\n",buff);
close(newsock); // close immediate and look for another some1 new
}
int main()
{
GIOChannel *in;
struct sockaddr_in my;
my.sin_addr.s_addr = INADDR_ANY;
my.sin_family = AF_INET;
my.sin_port = htons(3000);
//socket initiate root socket
int rsock = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
//allow re-use address
setsockopt(rsock,SOL_SOCKET,SO_REUSEADDR,(int*)1,sizeof(int));
//binding
bind(rsock,(struct sockaddr*)&my,sizeof(my));
//listen
listen(rsock,10);
in = g_io_channel_unix_new(rsock);
g_io_add_watch(in, G_IO_IN | G_IO_OUT | G_IO_HUP, (GIOFunc) deal, NULL);
GMainLoop *loop = g_main_loop_new(NULL,FALSE); // pengganti while(1) ato gtk_main_loop
g_main_loop_run(loop);
return 0;
}
and it get compiled :
$ gcc -o dengersocket_glib dengersocket_glib.c `pkg-config --cflags --libs glib-2.0`
and now listening and look forward any packet data from client
and the client send the following packet :
$ echo wew | nc -v localhost 3000
nc: connect to localhost port 3000 (tcp) failed: Connection refused
Connection to localhost 3000 port [tcp/*] succeeded!
and now the server receive following weird packet :
$ ./dengersocket_glib
data : �o=
and my question is, where is the fault on my code ?,
1.how to get the proper packet and every single client could connect to the server ? [solved]
2.the passing data is solved, but still just could accept only one client, how to get more than one client?
int recv_total;
should be
int recv_total = 0;
With the random garbage value your recv_total has due to lack of initialization, you'll also get random garbage data in buf unless recv_total just happened to be <128, and the first char in the buffer will be garbage unless recv_total happened to be 0.
EDIT:
Also, your accept call is wrong, you cast a size to void * but are supposed to pass a pointer to a socklen_t which should contain and receive the size of the sockaddr.
socklen_t ss = sizeof(income);
accept(..., &ss);
Then, check the return value from accept, see that you got a valid socket.
if (newsock == -1) {
printf("...");
}

Resources