|
/* tcp_client.c */
#include <stdio.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <string.h>
int main(int argc, char *argv[])
{
int socketfd;
struct sockaddr_in serveraddr;
char sendmessage[1500], receivemessage[1500];
socketfd = socket(AF_INET, SOCK_STREAM, 0);
memset(&serveraddr, 0, sizeof(serveraddr));
serveraddr.sin_family = AF_INET;
serveraddr.sin_port = htons(800);
serveraddr.sin_addr.s_addr=inet_addr(argv[1]);
if(connect(socketfd, (struct sockaddr *)&serveraddr, sizeof(serveraddr)) < 0)
printf("connect error");
while(fgets(sendmessage, 1500, stdin) != NULL)
{
write(socketfd, sendmessage, strlen(sendmessage));
while(read(socketfd, receivemessage, 1500) > 0)
{
fputs(receivemessage, stdout);
}
}
}
这是个回射tcp客户-服务器程序的客户端,不知是程序本生有问题那还是操作系统有问题还是校园网的原因,
gcc -o tcp_client tcp_client.c之后,./tcp_client 127.0.0.1时,就算服务器程序未开,connect()函数也正常返回,不显示error.可800端口根本没开着的程序阿!
但是就算服务器程序开着,用ip地址还是会出现connect error,
我超级郁闷了,这个是什么怪事阿,大虾急救阿,我已经郁闷好久了!!!
/* tcp_server.c */
#include <stdio.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <string.h>
int main(int argc, char *argv[])
{
int listenfd, connectfd;
struct sockaddr_in serveraddr, clientaddr;
socklen_t client;
ssize_t n;
char message[1500];
listenfd = socket(AF_INET, SOCK_STREAM, 0);
memset(&serveraddr, 0, sizeof(serveraddr));
serveraddr.sin_family = AF_INET;
serveraddr.sin_addr.s_addr = htonl(INADDR_ANY);
serveraddr.sin_port = htons(800);
bind(listenfd, (struct sockaddr *)&serveraddr, sizeof(serveraddr));
listen(listenfd, 10);
for(; ;)
{
client = sizeof(clientaddr);
connectfd = accept(listenfd, (struct sockaddr *)&clientaddr, &client);
write(connectfd, "hello", 5);
while((n = read(connectfd, message, 1500)) > 0)
{
write(connectfd, message, n);
}
}
} |
|