Last active
May 26, 2016 08:41
-
-
Save kaizawa/f4760449a456837c02734f71f010881a to your computer and use it in GitHub Desktop.
Simple socket program lisning on port 25
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <strings.h> | |
#include <unistd.h> | |
#include <sys/socket.h> | |
#include <netinet/in.h> | |
#include <netdb.h> | |
#include <syslog.h> | |
#include <libgen.h> | |
#include <arpa/inet.h> | |
#include <sys/time.h> | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <sys/types.h> | |
#include <signal.h> | |
#include <errno.h> | |
#include <stdarg.h> | |
#include <sys/stat.h> | |
#include <fcntl.h> | |
int main () { | |
int listener_fd, new_fd; | |
int on; | |
int remotelen = sizeof(struct sockaddr_in); | |
struct sockaddr_in local_sin, remote_sin; | |
if(( listener_fd = socket( AF_INET, SOCK_STREAM,0 )) < 0 ) { | |
printf("error socket"); | |
exit(1); | |
} | |
on = 1; | |
if((setsockopt(listener_fd, SOL_SOCKET, SO_REUSEADDR, (char *)&on, sizeof(on))) <0){ | |
printf("error setsockopt"); | |
exit(1); | |
} | |
memset((char *)&local_sin, 0x0, sizeof(struct sockaddr_in)); | |
memset((char *)&remote_sin, 0x0, sizeof(struct sockaddr_in)); | |
local_sin.sin_port = htons((short)25); | |
local_sin.sin_family = AF_INET; | |
local_sin.sin_addr.s_addr = htonl(INADDR_ANY); | |
if(bind(listener_fd,(struct sockaddr *)&local_sin,sizeof(struct sockaddr_in)) < 0 ){ | |
printf("error bind"); | |
exit(1); | |
} | |
if(listen(listener_fd, 5) < 0) { | |
printf("error listen"); | |
exit(1); | |
} | |
while (1) { | |
if((new_fd = accept(listener_fd,(struct sockaddr *)&remote_sin, &remotelen)) < 0){ | |
perror("accept"); | |
exit(-1); | |
} | |
printf("new fd=%d\n", new_fd); | |
int reading = 1; | |
while(reading){ | |
char databuf[10]; | |
int rsize; | |
char prev; | |
rsize = recv(new_fd, databuf, 10, 0); | |
if(rsize == 0){ | |
perror("connection closed"); | |
} else if(rsize < 0){ | |
perror("recv\n"); | |
exit(-1); | |
} | |
int i; | |
for( i = 0 ; i < rsize ; i++){ | |
printf("%c", databuf[i]); | |
if(databuf[i] == '.' && prev == '\n'){ | |
close(new_fd); | |
reading = 0; | |
break; | |
} | |
prev = databuf[i]; | |
} | |
} | |
printf("\n"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
gcc -lsocket -lnsl -o smtp smpt.c