当前位置: 技术问答>linux和unix
菜鸟问以下关于网络编程的问题
来源: 互联网 发布时间:2016-09-07
本文导语: int main ( int argc, char *argv[] ) { struct sockaddr_in saddr; struct hostent *hp; char hostname[HOSTLEN]; int sock_id, sock_fd; FILE *sock_fp; char *ctime(); time_t thetime; sock_id = socket(AF_INET, SOCK_STREAM, 0); if (sock_id == -1) { oops("socket error!...
int main ( int argc, char *argv[] )
{
struct sockaddr_in saddr;
struct hostent *hp;
char hostname[HOSTLEN];
int sock_id, sock_fd;
FILE *sock_fp;
char *ctime();
time_t thetime;
sock_id = socket(AF_INET, SOCK_STREAM, 0);
if (sock_id == -1)
{
oops("socket error!");
}
memset(&saddr, 0, sizeof(struct sockaddr_in));
gethostname(hostname, HOSTLEN);
hp = gethostbyname(hostname);
bcopy((void*)hp->h_addr, (void*)&saddr.sin_addr, hp->h_length);
saddr.sin_port = htons(PORTNUM);
saddr.sin_family = AF_INET;
if (bind(sock_id, (struct sockaddr*)&saddr, sizeof(saddr)) != 0)
{
oops("bind");
}
if (listen(sock_id, 1) != 0)
{
oops("listen");
}
while (1)
{
sock_fd = accept(sock_id, NULL, NULL);
printf("Wow! got a calln");
if (sock_fd == -1)
{
oops("accept");
}
sock_fp = fdopen(sock_fd, "w");
if (sock_fp == NULL)
{
oops("fdopen");
}
thetime = time(NULL);
fprintf(sock_fp, "the time here is..");
fprintf(sock_fp, "%s", ctime(&thetime));
fclose(sock_fp);
}
return EXIT_SUCCESS;
} /* ---------- end of function main ---------- */
我按书上编了一个能返回时间的服务器程序,
然后我在另一台电脑上(两台电脑由路由器链接,服务器已经在我电脑上运行)
我运行这个命令
telent zch-laptop 13000(zch-laptop为我电脑的名字,13000是端口号)
为什么没反应阿?按照书上说应该返回时间?
还有,我看是在不行,又编了一个客户端,在另一台机器上运行,仍然不行(程序肯定正确)。
是我还有什么地方没弄明白吧,还请大侠指点阿
|
#include
#include
#include
#include
#include
#include
#include
#include
#define HOSTLEN 124
#define PORTNUM 13000
int main ( int argc, char *argv[] )
{
struct sockaddr_in saddr;
struct hostent *hp;
char hostname[HOSTLEN];
int sock_id, sock_fd;
FILE *sock_fp;
char *ctime();
time_t thetime;
sock_id = socket(AF_INET, SOCK_STREAM, 0);
if (sock_id == -1)
{
printf("socket error!");
}
memset(&saddr, 0, sizeof(struct sockaddr_in));
gethostname(hostname, HOSTLEN);
hp = gethostbyname(hostname);
bcopy((void*)hp->h_addr, (void*)&saddr.sin_addr, hp->h_length);
saddr.sin_port = htons(PORTNUM);
saddr.sin_family = AF_INET;
if (bind(sock_id, (struct sockaddr*)&saddr, sizeof(saddr)) != 0)
{
printf("bind");
}
if (listen(sock_id, 1) != 0)
{
printf("listen");
}
while (1)
{
sock_fd = accept(sock_id, NULL, NULL);
printf("Wow! got a calln");
if (sock_fd == -1)
{
printf("accept");
}
sock_fp = fdopen(sock_fd, "w");
if (sock_fp == NULL)
{
printf("fdopen");
}
thetime = time(NULL);
fprintf(sock_fp, "the time here is..");
fprintf(sock_fp, "%s", ctime(&thetime));
fclose(sock_fp);
}
return EXIT_SUCCESS;
}
这是你的代码可以运行的
正常运行 你用telent ip 13000的方式试试
[root@ns ~]# telnet localhost 13000
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
Wow! got a call
the time here is..Wed Jun 30 17:09:19 2010
Connection closed by foreign host.