TCP协议:
传输层协议
有连接
可靠传输
面向字节流
地址转换函数:
#include
#include
#include
int inet_aton(const char *cp, struct in_addr *inp);
in_addr_t inet_addr(const char *cp);
char *inet_ntoa(struct in_addr in);//4字节转换位点分十进制
这个函数返回了一个char* ,说明函数自己内部为我们申请了一块内存来保存IP的结果,但这个函数将结果放到了静态存储区,所以不需要我们手动去释放,但是在第二次调用的时候会覆盖上一次的结果。
const char *inet_ntop(int af,//指定地址类型 const void *src,
char *dst, socklen_t size);
以下是一个简单的单进程TCP网络程序
//服务器
#include
#include
#include
#include
#include
#include
#include
#include
#define MAX 128
void service(int sock,char* ip,int port)
{
char buf[MAX];
while(1)
{
buf[0] = 0;
ssize_t s = read(sock,buf,sizeof(buf)-1);
if(s > 0)
{
buf[s] = 0;
printf("[%s:%d] say# %s\n",ip,port,buf);
write(sock,buf,strlen(buf));
}
else if(s == 0)
{
printf("client [%s:%d] quit\n",ip,port);
break;
}
else
{
printf("read error\n");
break;
}
}
}
int statup(char* ip,int port)
{
int sock = socket(AF_INET,SOCK_STREAM,0);
if(sock < 0)
{
printf("socket error\n");
exit(2);
}
struct sockaddr_in local;
local.sin_family = AF_INET;
local.sin_addr.s_addr = inet_addr(ip);
local.sin_port = htons(port);
if(bind(sock,(struct sockaddr*)&local,sizeof(local)) < 0)
{
printf("bind error\n");
exit(3);
}
if(listen(sock,5) < 0)
{
printf("listen error\n");
exit(4);
}
return sock;
}
// ./tcpServer 127.0.0.1 8080
int main(int argc,char* argv[])
{
if(argc != 3)
{
printf("Usage: %s[ip][port]\n",argv[0]);
return 1;
}
int listen_sock = statup(argv[1],atoi(argv[2]));
struct sockaddr_in peer;
char ipBuf[24];
for(;;)
{
ipBuf[0] = 0;
socklen_t len = sizeof(peer);
int new_sock = accept(listen_sock,(struct sockaddr*)&peer,&len);
if(new_sock < 0)
{
printf("accept error\n");
continue;
}
inet_ntop(AF_INET,(const char*)&peer.sin_addr,ipBuf,sizeof(ipBuf));
int port = ntohs(peer.sin_port);
printf("get a new connet,[%s:%d]\n",ipBuf,port);
service(new_sock,ipBuf,port);
close(new_sock);
}
return 0;
}
//客户端
#include
#include
#include
#include
#include
#include
#include
#include
#define MAX 128
// ./tcpClient 127.0.0.1 8080
int main(int argc,char* argv[])
{
if(argc != 3)
{
printf("Usage: %s [ip] [port]\n",argv[0]);
exit(1);
}
int sock = socket(AF_INET,SOCK_STREAM,0);
if(sock < 0)
{
printf("socket error\n");
exit(2);
}
struct sockaddr_in server;
server.sin_family = AF_INET;
server.sin_port = htons(atoi(argv[2]));
server.sin_addr.s_addr = inet_addr(argv[1]);
if(connect(sock,(struct sockaddr*)&server,sizeof(server)) < 0)
{
printf("connect error\n");
exit(3);
}
char buf[MAX];
while(1)
{
printf("please Enter# ");
fflush(stdout);
ssize_t s = read(0,buf,sizeof(buf)-1);
if(s > 0)
{
buf[s-1] = 0;
if(strcmp("quit",buf) == 0)
{
printf("client quit\n");
break;
}
write(sock,buf,strlen(buf));
s = read(sock,buf,sizeof(buf)-1);
buf[s] = 0;
printf("Server Echo %s\n",buf);
}
}
close(sock);
return 0;
}