tcp client
#include <arpa/inet.h>
#include <unistd.h>
#include <netinet/in.h>
#include <stdio.h>
#include <strings.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <time.h>
#define BIND_PORT 80
#define LISTENQ 10
int main(int argc, char **argv)
{
int ret;
int socket_fd;
struct sockaddr_in server_sockaddr;
struct sockaddr_in clinet_sockaddr;
time_t ticks;
char buf[100] = {0};
int str_len;
if (2 != argc) {
printf("Usage:\n");
printf(" %s <serverip>\n", argv[0]);
return -1;
}
/* 创建套接字 */
socket_fd = socket(AF_INET, SOCK_STREAM, 0);
if (-1 == socket_fd) {
perror("socket");
return -1;
}
/* 连接服务器 */
server_sockaddr.sin_family = AF_INET;
server_sockaddr.sin_port = htons(BIND_PORT);
if (!inet_aton(argv[1], (struct in_addr *)&server_sockaddr.sin_addr.s_addr)) {
printf("serverip error : %s\n", argv[1]);
return -1;
}
ret = connect(socket_fd, (struct sockaddr *)&server_sockaddr, sizeof(struct sockaddr));
if (-1 == ret) {
perror("connect");
return -1;
}
/* 获取时间 */
ret = recv(socket_fd, buf, sizeof(buf), 0);
if (ret) {
printf("time : %s\n", buf);
}
else {
perror("recv");
return -1;
}
close(socket_fd);
return 0;
}
TCP server
#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdio.h>
#include <strings.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <time.h>
#define BIND_PORT 80
#define LISTENQ 10
int main(int argc, char **argv)
{
int ret;
int server_fd;
int client_fd;
struct sockaddr_in server_sockaddr;
struct sockaddr_in clinet_sockaddr;
socklen_t socklen;
time_t ticks;
char buf[100] = {0};
int str_len;
printf("%s %s %d\n", __FILE__, __FUNCTION__, __LINE__);
/* 创建套接字 */
server_fd = socket(AF_INET, SOCK_STREAM, 0);
if (-1 == server_fd) {
perror("socket");
return -1;
}
/* 绑定端口号 */
server_sockaddr.sin_family = AF_INET;
server_sockaddr.sin_port = htons(BIND_PORT);
server_sockaddr.sin_addr.s_addr = htonl(INADDR_ANY);
ret = bind(server_fd, (struct sockaddr *)&server_sockaddr, sizeof(struct sockaddr));
if (-1 == ret) {
perror("bind");
return -1;
}
/* 把套接字转换成一个监听套接字 */
ret = listen(server_fd, LISTENQ);
if (-1 == ret) {
perror("listen");
return -1;
}
while (1)
{
/* 接受客户端发来的连接请求 */
client_fd = accept(server_fd, (struct sockaddr *)&clinet_sockaddr, &socklen);
if (-1 == client_fd) {
perror("accept");
continue;
}
printf("connection from %s, port %d\n", inet_ntoa(clinet_sockaddr.sin_addr),
ntohs(server_sockaddr.sin_port));
/* 获取时间 */
ticks = time(NULL);
bzero(buf, sizeof(buf));
str_len = sprintf(buf, "%s", ctime(&ticks));
/* 发送时间到客户端 */
ret = send(client_fd, buf, str_len, 0);
if (-1 == ret) {
perror("send");
continue;
}
}
return 0;
}