

#include <stdio.h>
#include <stdlib.h>
#include <fstream>
#include <iostream>
#include <string.h>
#include <string>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <time.h>
int getpeeraddr(int sockfd)
{
char peeraddrstr[60];
char peerip[18];
struct sockaddr_in peeraddr;
socklen_t len;
string timearg = gettime();
int ret = getpeername(sockfd, (struct sockaddr *)&peeraddr, &len);
if (ret < 0)
return 0;
sprintf(peeraddrstr, "time: %s\npeer address: %s:%d\n\n", timearg.c_str(), inet_ntop(AF_INET, &peeraddr.sin_addr, peerip, sizeof(peerip)), ntohs(peeraddr.sin_port));
ofstream out("/home/connectlog", ios::app);
out.write(peeraddrstr, strlen(peeraddrstr));
out.close();
}
//获取当前日期及时间
string gettime()
{
time_t t;
struct tm *tm;
char buf[20];
t=time(NULL);
tm=localtime(&t);
snprintf(buf, 20, "%04d%02d%02d%02d%02d%02d", tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday, tm->tm_hour, tm->tm_min, tm->tm_sec);
string sendmsg(buf);
return sendmsg;
}
原创文章,作者:苏葳,如需转载,请注明出处:https://www.swmemo.com/309.html
