63 lines
1.4 KiB
C
63 lines
1.4 KiB
C
#include <netinet/in.h>
|
|
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <string.h>
|
|
#include <sys/socket.h>
|
|
#include <unistd.h>
|
|
|
|
#define LINESIZE 128
|
|
|
|
void error(char *msg){
|
|
perror(msg);
|
|
exit(1);
|
|
}
|
|
|
|
int main (int argc, char *argv[]){
|
|
int sockfd;
|
|
int newsockfd;
|
|
int portno;
|
|
int clilen;
|
|
int n;
|
|
char buffer[LINESIZE];
|
|
struct sockaddr_in serv_addr;
|
|
struct sockaddr_in cli_addr;
|
|
if (argc < 2){
|
|
fprintf(stderr, "ERROR, no port provided\n");
|
|
exit(1);
|
|
}
|
|
|
|
sockfd = socket(PF_INET, SOCK_STREAM, 0);
|
|
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);
|
|
printf("Server is waiting for the message, please wait...\n");
|
|
|
|
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");
|
|
}
|
|
bzero(buffer, LINESIZE);
|
|
n = read(newsockfd, buffer, LINESIZE);
|
|
if (n < 0){
|
|
error("ERROR reading from socket");
|
|
}
|
|
printf("The message is: %s", buffer);
|
|
fprintf(stderr, "The mesaage contains %d bytes.\n", n);
|
|
|
|
close(sockfd);
|
|
|
|
return 0;
|
|
} |