Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <netdb.h>
#define MYPORT 9034
int main(void)
{
int sockfd;
char ch;
struct sockaddr_in my_addr, their_addr;
char buffer[1000];
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if(sockfd == -1)
{
printf("ERROR!!");
perror("socket");
getchar();
exit(1);
}
my_addr.sin_family = AF_INET;
my_addr.sin_addr.s_addr = INADDR_ANY;
my_addr.sin_port = htons(MYPORT);
memset(&(my_addr.sin_zero), '\0', 8);
if( (bind(sockfd,(struct sockaddr *)&my_addr,sizeof(struct sockaddr)))==-1)
{
perror("bind");
exit(1);
}
if( listen(sockfd, 10) == -1 )
{
printf("ERROR!!");
perror("listen");
getchar();
exit(1);
}
scanf("%c", &ch);
while( ch != 'q')
{
int state = sizeof(struct sockaddr);
int new_fd = accept(sockfd, (struct sockaddr *)&their_addr, &state);
if(new_fd == -1)
{
perror("accept");
exit(1);
}
state = send(new_fd, buffer, strlen(buffer), 0);
sprintf(buffer, "%s has connected.\n", inet_ntoa(their_addr.sin_addr));
if(state == -1)
{
printf("ERROR!!");
perror("send");
getchar();
exit(1);
}
}
return 0;
}
ERRORS:
Code:
untitled.c:49: warning: pointer targets in passing argument 3 of ‘accept’ differ in signedness
untitled.c:56: warning: implicit declaration of function ‘inet_ntoa’
untitled.c:56: warning: format ‘%s’ expects type ‘char *’, but argument 3 has type ‘int’
The compilation was finished successfully though but it doesn't work properly.
How to fix it?
I might be missing some headers.
BTW,
Is there any other function that I could get 1 character? fgets doesn't work for characters just for strings, and gets & scanf are dangerous.
Any suggestions?