#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <signal.h>
#define SIZE sizeof(struct sockaddr_in)
void catcher(int sig);
int newsockfd;
int main()
{
int sockfd;
char c[100];
struct sockaddr_in server = {AF_INET, 2004, INADDR_ANY};
static struct sigaction act;
act.sa_handler = catcher;
sigfillset(&(act.sa_mask));
sigaction(SIGPIPE, &act, NULL);
/* set up the transport end point */
if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
{
perror("socket call failed");
exit(1);
}
printf("socket call success\n");
/* bind an address to the end point */
if(bind(sockfd, (struct sockaddr *)&server, SIZE) == -1)
{
perror("bind call failed");
exit(1);
}
printf("bind call success\n");
/* start listenning for incoming connections */
if(listen(sockfd, 5) == -1)
{
perror("listen call failed");
exit(1);
}
printf("listen call success\n");
for(;;)
{
/* accept a connection */
if((newsockfd = accept(sockfd, NULL, NULL)) == -1)
{
perror("accept call failed");
continue;
}
printf("new client\n");
/*spawn a child to deal with the connection */
if(fork() == 0)
{
while(recv(newsockfd, &c, sizeof(c), 0) > 0)
{
int i = 0;
do{
c[i] = toupper(c[i]);
i ++;
}while(c[i] != '\0');
//c = toupper(c);
send(newsockfd, &c, sizeof(c), 0);
}
/* when client is no longer sending information the socket can be
closed and the child process terminated */
printf("client colsed\n");
close(newsockfd);
exit(0);
}
/* parent doesn't need the newsockfd */
close(newsockfd);
}
}
void catcher(int sig)
{
close(newsockfd);
exit(0);
}
编译及运行情况:
[root@tjsms testdir]# gcc -o srvsocket srvsocket.c
[root@tjsms testdir]# srvsocket
socket call success
bind call success
listen call success
telnet的情况:
telnet localhost 2004
Trying 127.0.0.1...
telnet: connect to address 127.0.0.1: Connection refused
直接telnet IP也不行.
但是它可以和使用c写的client通信.
原始程序来自:电子工业出版社<Unix 系统编程(第二版)>P202 - 204
我初步估计可能是端口号表示的方法c和一般不同.请高手指教
3 个解决方案
#1
try
struct sockaddr_in server = {AF_INET, htons(2004), INADDR_ANY};
struct sockaddr_in server = {AF_INET, htons(2004), INADDR_ANY};
#2
telent 的默认端口不是23吗?
#3
to:sharkhuang(爱情和程序都读不懂)
telnet可以指定端口.默认的是23
telnet ip port
telnet可以指定端口.默认的是23
telnet ip port
#1
try
struct sockaddr_in server = {AF_INET, htons(2004), INADDR_ANY};
struct sockaddr_in server = {AF_INET, htons(2004), INADDR_ANY};
#2
telent 的默认端口不是23吗?
#3
to:sharkhuang(爱情和程序都读不懂)
telnet可以指定端口.默认的是23
telnet ip port
telnet可以指定端口.默认的是23
telnet ip port