linux socket编程代码
发布网友
发布时间:2022-05-06 05:44
我来回答
共1个回答
热心网友
时间:2022-06-28 19:54
#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<netdb.h>
char *host_name="127.0.0.1";
int port=7778;
struct student
{
char name[20];
char num[20];
float score;
}t={"xiejian","200701415",89.9};
int main ( )
{
char buf[502];
int socket_descriptor;
struct sockaddr_in pin;
bzero(&pin,sizeof(pin));
pin.sin_family=AF_INET;
inet_pton(AF_INET,host_name,&pin.sin_addr);
pin.sin_port=htons(port);
if((socket_descriptor=socket(AF_INET,SOCK_STREAM,0))==-1)
{
perror("Error openung socket!\n");
exit(1);
}
if(connect(socket_descriptor,(void *)&pin,sizeof (pin))==-1)
{
perror("can not connecting to server!\n");
exit (1);
}
printf("Send message to server ...\n");
//memset(buf,0,502);
//memcpy(buf,(void *)&t,sizeof(t));
//sprintf(buf,"%s %d",t.name,t.num);
//printf("the first string : %s\n",buf);
if(send(socket_descriptor,(void *) &t,sizeof(t),0)==-1)
{
perror("can not send message!\n");
exit (1);
}
printf("waiting for response from server!\n");
memset(buf,0,502);
if(recv(socket_descriptor,buf,sizeof(buf),0)==-1)
{
perror("can not receive response !\n");
exit (1);
}
printf("\n Response from server : \n");
memcpy((struct student *)&t,buf,sizeof(buf));
//printf("the string : %s \n",rebuf);
printf("--%s--%s--%5.1f--\n",t.name,t.num,t.score);
close (socket_descriptor);
}
/* 注意在send 结构体时应该把结构体强制类型转换为void * 型
** 接受之后又要强制转换回结构体型!否则则穿过来的是结构体的
** 一部分!
*/
下面是服务端
#include<stdio.h>
#include<stdlib.h>
#include<netinet/in.h>
#include<sys/socket.h>
#include<arpa/inet.h>
#include<netdb.h>
int port=7778;
struct student
{
char name[20];
char num[20];
float score;
}t;
main()
{
struct sockaddr_in sin;
struct sockaddr_in pin;
int sock_descriptor;
int temp_sock_descriptor;
int size_of_addr;
//struct cfg a;
char buf[502];
int i,lenth;
sock_descriptor=socket(AF_INET,SOCK_STREAM,0);
if(sock_descriptor==-1)
{
perror("socket!\n");
exit(1);
}
bzero(&sin,sizeof(sin));
sin.sin_addr.s_addr=INADDR_ANY;
sin.sin_port=htons(port);
if(bind(sock_descriptor,(struct sockaddr *)&sin,sizeof (sin))==-1)
{
perror("bind!\n");
exit(1);
}
if(listen (sock_descriptor,20)==-1)
{
perror("listen!\n");
exit(1);
}
printf("Waiting for accepting connection from client!\n");
while(1)
{
printf("the process is waiting here!\n");
temp_sock_descriptor=accept(sock_descriptor, (struct sockaddr *)&pin,&size_of_addr);
if(temp_sock_descriptor==-1)
{
perror("call to accept!\n");
exit (1);
}
memset(buf,0,502);
if(recv(temp_sock_descriptor,buf,sizeof(buf),0)==-1)
{
perror("recv!\n");
exit (1);
}
printf("received : \n");
//printf("the recv buf is :%s\n",buf);
memcpy((struct student *) &t,buf,sizeof(buf));
printf("--%s--%s--%5.1f--\n",t.name,t.num,t.score);
if(send (temp_sock_descriptor,(void *) &t,sizeof(t),0)==-1)
{
perror("send!\n");
exit(1);
}
close (temp_sock_descriptor);
}
}