linux进程通信 获取远程系统时间的例子
server.c
--------------------
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#define LOCAL_IP "192.168.59.194"
#define LOCAL_PORT 8888
struct sockaddr_in local_sk_addr, client_sk_addr;
int fd_sock,full_sock;
char buf[27];
struct timeval tv;
int length = 0;
int main(void)
{
int lsn_id;
fd_set fdset;
fd_sock = socket(AF_INET, SOCK_STREAM, 0);
bzero(&local_sk_addr, sizeof(local_sk_addr));
local_sk_addr.sin_port = htons(LOCAL_PORT);
local_sk_addr.sin_family = AF_INET;
local_sk_addr.sin_addr.s_addr = inet_addr(LOCAL_IP);
bind(fd_sock, (struct sockaddr*)&local_sk_addr, sizeof(local_sk_addr));
lsn_id = listen(fd_sock, 5);
if (lsn_id != -1)
printf("listen on port %d\n:", LOCAL_PORT);
FILE * file = NULL;
file = fopen("out.txt", "w+");
if (NULL == file){
printf("open out.txt failed.\n");}
while (1)
{
FD_ZERO(&fdset);
if ((full_sock = accept(fd_sock, NULL, NULL))>0 )
{
printf("remote connected!\n");
break;
}
}
while(2)
{
// printf("full_sock:%d\n", full_sock);
//FD_SET(full_sock, &fdset);
//tv.tv_sec = tv.tv_usec = 0;
bzero(buf, 27);
if(0 < recv(full_sock, buf, 26 , 0))
{
fputs(buf, file);
// printf("%s\n", "in!");
printf("remote says:%s\n", buf);
// printf("\n");
}
}
//sleep(1);
/*
if (select(full_sock + 1, &fdset, NULL, NULL, &tv) > 0)
{
printf("data recving!\n");
if(FD_ISSET(full_sock, &fdset))
{
bzero(buf, 27);
if(recv(full_sock, buf, 27 , 0))
{
printf("%s\n", "in!");
printf("remote says:%s\n", buf);
printf("\n");
}
}
}
*/
//close(full_sock);
//close(fd_sock);
// fclose(file);
}
client.c
_____________________________________
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#define REMOTE_IP "192.168.59.194"
#define REMOTE_PORT 8888
struct sockaddr_in remote_sk_addr;
int fd_sock;
char buf[27];
struct tm l_time;
void local_time(char* buf)
{
struct timeval tv;
time_t time;
struct tm* st_tm;
gettimeofday(&tv, NULL);
time = tv.tv_sec;
st_tm = localtime((const time_t*)&time);
sprintf(buf,"%d-%d-%d %d:%d:%d.%ld\n",
st_tm->tm_year + 1900,
st_tm->tm_mon + 1,
st_tm->tm_mday,
st_tm->tm_hour,
st_tm->tm_min,
st_tm->tm_sec,
tv.tv_usec);
}
int main(void)
{
fd_set fdset;
fd_sock = socket(AF_INET, SOCK_STREAM, 0);
bzero(&remote_sk_addr, sizeof(remote_sk_addr));
remote_sk_addr.sin_port = htons(REMOTE_PORT);
remote_sk_addr.sin_family = AF_INET;
remote_sk_addr.sin_addr.s_addr = inet_addr(REMOTE_IP);
connect(fd_sock, (struct sockaddr*)&remote_sk_addr, sizeof(remote_sk_addr));
//printf("fd_sock:%d\n", fd_sock);
if(fd_sock != -1)
{
printf("connected to remote!");
}
printf("\n");
while (1)
{
// FD_ZERO(&fdset);
// FD_SET(fd_sock, &fdset);
bzero(buf, 27);
local_time(buf);
printf("%s\n", buf);
// send(fd_sock, buf, 27, 0);
sendto(fd_sock, buf, 27, 0, (struct sockaddr*) &remote_sk_addr,sizeof(remote_sk_addr));
sleep(2);
}
// close(fd_sock);
}