Skip to content

Instantly share code, notes, and snippets.

@liuchang0812
Created July 23, 2014 09:59
Show Gist options
  • Save liuchang0812/9d6d1a5887930cfe16be to your computer and use it in GitHub Desktop.
Save liuchang0812/9d6d1a5887930cfe16be to your computer and use it in GitHub Desktop.
#include <iostream>
#include <ctime>
extern "C"
{
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <signal.h>
}
using namespace std;
void signal_handler(int siganl)
{
cout << "pressed CTRL+C, exiting" << endl;
_exit(0);
}
int main()
{
signal(SIGINT, signal_handler);
int sock = socket(AF_INET, SOCK_STREAM,0);
if( sock == NULL)
{
cout << "create sock error" << endl;
_exit(0);
}
struct sockaddr_in server_address;
int conn;
time_t ticks;
char buffer[1025];
memset(&server_address, 0, sizeof server_address);
server_address.sin_family = AF_INET;
server_address.sin_addr.s_addr = htonl(INADDR_ANY);
server_address.sin_port = htons(711);
int ret = bind(sock, (struct sockaddr*)&server_address, sizeof server_address);
listen(sock, 10);
while (true)
{
conn = accept(sock, (struct sockaddr*)NULL, NULL);
ticks = time(NULL);
sprintf(buffer, "%s\r\n", ctime(&ticks));
write(conn, buffer, sizeof buffer);
close(conn);
}
close(sock);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment