客户端:client.c
#include
#include
#include
#include
#include
#include
#include
#include
#include
int main(int argc, char **argv[])
{
struct sockaddr_in addr, servaddr;
int s, err;
int port = 8383;
char IP[100] = "10.144.15.234";
char msg[100]="Hello \n";
if((s = socket(AF_INET, SOCK_STREAM, 0)) < 0) printf("error in socket\n");
bzero(&addr, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
addr.sin_addr.s_addr = inet_addr(IP);
err = connect(s, (struct sockaddr *) &addr, sizeof(addr));
if (err <0) printf("error:%d\n",errno);
send(s, msg, sizeof(msg), 0);
}
编译参数:
cc -o client client.c -lsocket -lnsl
服务器端:host.c
#include
#include
#include
#include
#include
#include
#include
#include
#include
int main(int argc, char **argv[])
{
struct sockaddr_in addr, caddr;
int s,cs, len, err;
int port = 8383;
char IP[100] = "10.144.15.234";
char msg[100];
if((s = socket(AF_INET, SOCK_STREAM, 0)) < 0) printf("error in socket\n");
bzero(&addr, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
addr.sin_addr.s_addr = htonl(INADDR_ANY);
err = bind(s, (struct sockaddr *)&addr, sizeof(addr));
if(err < 0) {
printf("bind error\n");
printf("error = %d : ",errno);
printf("EBADF, EACCESS, ENOTSOCK=%d,%d,%d\n", EBADF,EACCES,ENOTSOCK);
exit(0);
}
listen(s, SOCK_STREAM);
len = sizeof(addr);
while(1){
cs = accept(s, (struct sockaddr *)&addr, &len);
if(cs >0) {
read(cs, msg, 100);
printf("now recv %s\n",msg);
}
else sleep(1);
}
}
编译参数:
cc -o host host.c -lsocket -lnsl
阅读(1162) | 评论(0) | 转发(0) |