网络编程-基于TCP/UDP的客户端获取服务器时间例子

本文介绍了TCP和UDP网络编程模型,包括TCP的三次握手和四次挥手过程,以及网络字节序的转换函数。通过实例展示了如何实现基于TCP/UDP的客户端获取服务器时间,同时讲解了套接字地址结构和IP地址转换函数的使用。
摘要由CSDN通过智能技术生成

TCP传输控制协议
向用户进程提供可靠的全双工字节流(字节流:给每一个字节编序)

UDP用户数据报协议
是一种无连接的协议

获取时间服务的客户端
client

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
#include <fcntl.h>
#include <arpa/inet.h>
int main(int argc,char *argv[])
{
   
        int sockfd;
        struct sockaddr_in servaddr;
        char buf[100];//存储读取的内容
        int bytes;//存储读取的字节数
 
        if((sockfd = socket(AF_INET,SOCK_STREAM,0)) < 0)//创建套接字
        {
   
                printf("socket error\n");
                return -1;
        }
        //结构体中成员变量初始化为0     
        bzero(&servaddr,sizeof(servaddr));
        //初始化成员变量
        servaddr.sin_family = AF_INET;//IPv4
        servaddr.sin_addr.s_addr = inet_addr("192.168.1.12");//转换为地址格式
        servaddr.sin_port = htons(8888);//主机序转换到网络序
        //连接服务器
        if(connect(sockfd,(struct sockaddr *)&servaddr,sizeof(servaddr)) < 0)//绑定服务器ip和端口到>套结字
        {
   
                perror("connect error");
                return -2;
        }
        //存储读取的数据和读取的字节数
        bytes = read(sockfd,buf,100);
        if(bytes < 0)
        {
   
                printf("Error ,read failed\n");
                close(sockfd);
                return -3;
        }
        //如果读取的字节数为0 ,就说明连接已经关闭了
        if(0 == bytes)
        {
   
                printf("Server close connection\n");
                close(sockfd);
                return -4;
 
        }
        //打印读取的字节数和读取的内容
        printf("read bytes %d\n",bytes);
        printf("Time: %s\n",buf);
        //关闭套结字
        close(sockfd);
        return 0;
}

运行结果

read bytes 25
Time: Tue Jul 21 14:45:10 2020

server

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值