- 论坛徽章:
- 0
|
刚学习我那刚落编程写了一个简单的本机通讯,可结果出错了!
server.c
#include<stdio.h>
#include<stdlib.h>
#include<errno.h>
#include<string.h>
#include<sys/types.h>
#include<netinet/in.h>
#include<sys/socket.h>
#include<sys/wait.h>
main()
{
int sockfd,new_fd,numbytes;
struct sockaddr_in my_addr;
struct sockaddr_in their_addr;
int sin_size;
char buff[215];
//建立套接口
if((sockfd =socket(AF_INET,SOCK_STREAM,0)) == -1)
{
perror("socket" ;
exit(1);
}
//初始化结构体,并绑定2323端口
my_addr.sin_family = AF_INET;
my_addr.sin_port = htons(2323);
my_addr.sin_addr.s_addr = INADDR_ANY;
bzero(&(my_addr.sin_zero), ;
//绑定套接口
if(bind(sockfd,(struct sockaddr *)&my_addr,sizeof(struct sockaddr)) == -1)
{
perror("bind" ;
exit(1);
}
//创建监听套接口
if(listen(sockfd,10) == -1)
{
perror("listen" ;
exit(1);
}
//等待连接
while(1)
{
printf("服务器等待消息\n" ;
sin_size = sizeof(struct sockaddr_in);
perror("server is run" ;
//如果建立连接,将产生一个全新的套接字
if((new_fd = accept(sockfd,(struct sockaddr *)&their_addr,&sin_size)) == -1)
{
perror("accept" ;
exit(1);
}
recv(new_fd,buff,strlen(buff),0);
printf("来自客户端信息长度:%d\n信息为: ",strlen(buff));
send(new_fd,buff,strlen(buff),0);
puts(buff);
close(new_fd);
}
close(sockfd);
}
=========================================================
client.c
#include<string.h>
#include<sys/types.h>
#include<sys/socket.h>
#include <stdio.h>
#include<stdlib.h>
#include <unistd.h>
#include <netinet/in.h>
#define DEST_IP "192.168.0.100"
#define DEST_PORT 2323
int main()
{
int sockfd,result;
char ch[10];
/*用来储存远程信息*/
struct sockaddr_in my_addr;
/*进行错误检查!!*/
sockfd = socket(AF_INET,SOCK_STREAM,0);
/*主机字节顺序*/
my_addr.sin_family = AF_INET;
/* 网络字节顺序,短整形*/
my_addr.sin_port = htons(DEST_PORT);
my_addr.sin_addr.s_addr = inet_addr(DEST_IP);
/*将剩下的结构中空间置0*/
bzero(&(my_addr.sin_zero), ;
/*对connect进行检查*/
result=connect(sockfd,(struct sockaddr *)&my_addr,sizeof(struct sockaddr));
if(result == -1)
{
perror("connect:" ;
exit(1);
}
write(sockfd,"Hello!",6);
read(sockfd,&ch,strlen(ch));
puts(ch);
close(sockfd);
return(0);
}
=================================================
结果
服务端:
来自客户端信息长度:16
信息为: HelloX |
|