unix网络编程 大哥进来帮帮忙
那位大哥帮帮忙阿,小弟我刚学unix网络编程,遇到点问题,希望给解答下。
下面两个代码,分别运行时都报错,函数的返回值是-1,connect() bind()
client:
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<strings.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<netdb.h>
int main()
{
int client_socket;
struct sockaddr_in server_add;
time_t t;
client_socket=socket(AF_INET,SOCK_STREAM,0);
if(client_socket== -1)
{
printf("socket() error\n");
return -1;
}
bzero(&server_add,sizeof(server_add));
server_add.sin_family=AF_INET;
server_add.sin_port=htons(8080);
server_add.sin_addr.s_addr=htonl(INADDR_ANY);
if(connect(client_socket,(struct sockaddr *)(&server_add),sizeof(struct sockaddr))== -1){
printf("connect() error\n");
return 0;
}
recv(client_socket,(void *)&t,sizeof(time_t),0);
printf("Time is %s\n",ctime(&t));
printf("OK\n");
}
server:
#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<time.h>
#include<netdb.h>
#include<stdlib.h>
#include<string.h>
int main()
{
struct sockaddr_in server_add;
struct sockaddr_in client_add;
socklen_t addrlen;
int server_socket, client_socket;
server_socket=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
time_t t;
t=time(NULL);
bzero(&server_add,sizeof(server_add));
server_add.sin_family=AF_INET;
server_add.sin_port=8080;
server_add.sin_addr.s_addr=htonl(INADDR_ANY);
if(bind(server_socket,(struct sockaddr *)(&server_add),sizeof(server_add))== -1)
{
printf("bind() error\n");
return -1;
}
listen(server_socket,5);
addrlen = sizeof(client_add);
if(client_socket=accept(server_socket,(struct sockaddr *)&server_add,&addrlen))
{
printf("accept() error\n");
return -1;
}
send(client_socket,(time_t *)&t,sizeof(time_t),0);
return 0;
}
------解决方案--------------------
client:
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h&