Chinaunix首页 | 论坛 | 博客
  • 博客访问: 762050
  • 博文数量: 230
  • 博客积分: 6330
  • 博客等级: 准将
  • 技术积分: 2188
  • 用 户 组: 普通用户
  • 注册时间: 2009-07-10 15:55
个人简介

脚踏实地

文章分类

全部博文(230)

文章存档

2017年(1)

2016年(7)

2015年(10)

2014年(32)

2013年(24)

2012年(33)

2011年(50)

2010年(30)

2009年(43)

分类: 系统运维

2011-09-01 20:05:11

From:

TCP
server socket流程:socket()创建套接字,bind()绑定,listen()监听,accept()接收然后才是send(),recv()什么 的,最后关闭。

client
socket流程: socket(),connect(),recv(),send()最后close()。

注意一:
Linux服务器 1024 以下的端口号必须以超级管理员身份使用,或者授权。这个和Windows就不一样。
也就是说,楼主如果使用默认的端口号7,则运行你的这个程序应先切换到root身份,然后再这个权限下运行你写的那个程序。
以普通用户身份,系统不会把1024下的端口号给你用的。

//-------
建议在做Linux下网络编程的的时候,实验端口最好在10000以上,因为如果你的Linux装的服务软件多的话,可能会遇到端口号冲突的问题。别让这小问题绊住你。

端口号取值范围 0 - 65535(即2的16次方)



编译 gcc -o TCPEchoClient TCPEchoClient.c DieWithError.c
对于编译好的 程序 ./TCPEchoClient 127.0.0.1 "echo this"  
如果程序运行结果正常 :Recived :echo this 
但是显示 connect refuse 
TCPEchoClient.c
C/C++ code
  1. #include <stdio.h> /* for printf() and fprintf() */
  2. #include <sys/socket.h> /* for socket(), connect(), send(), and recv() */
  3. #include <arpa/inet.h> /* for sockaddr_in and inet_addr() */
  4. #include <stdlib.h> /* for atoi() and exit() */
  5. #include <string.h> /* for memset() */
  6. #include <unistd.h> /* for close() */

  7. #define RCVBUFSIZE 32 /* Size of receive buffer */

  8. void DieWithError(char *errorMessage); /* Error handling function */

  9. int main(int argc, char *argv[])
  10. {
  11.     int sock; /* Socket descriptor */
  12.     struct sockaddr_in echoServAddr; /* Echo server address */
  13.     unsigned short echoServPort; /* Echo server port */
  14.     char *servIP; /* Server IP address (dotted quad) */
  15.     char *echoString; /* String to send to echo server */
  16.     char echoBuffer[RCVBUFSIZE]; /* Buffer for echo string */
  17.     unsigned int echoStringLen; /* Length of string to echo */
  18.     int bytesRcvd, totalBytesRcvd; /* Bytes read in single recv()
  19.                                         and total bytes read */

  20.     if ((argc < 3) || (argc > 4)) /* Test for correct number of arguments */
  21.     {
  22.        fprintf(stderr, "Usage: %s []\n",
  23.                argv[0]);
  24.        exit(1);
  25.     }

  26.     servIP = argv[1]; /* First arg: server IP address (dotted quad) */
  27.     echoString = argv[2]; /* Second arg: string to echo */

  28.     if (argc == 4)
  29.         echoServPort = atoi(argv[3]); /* Use given port, if any */
  30.     else
  31.         echoServPort = 7; /* 7 is the well-known port for the echo service */

  32.     /* Create a reliable, stream socket using TCP */
  33.     if ((sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
  34.         DieWithError("socket() failed");

  35.     /* Construct the server address structure */
  36.     memset(&echoServAddr, 0, sizeof(echoServAddr)); /* Zero out structure */
  37.     echoServAddr.sin_family = AF_INET; /* Internet address family */
  38.     echoServAddr.sin_addr.s_addr = inet_addr(servIP); /* Server IP address */
  39.     echoServAddr.sin_port = htons(echoServPort); /* Server port */

  40.     /* Establish the connection to the echo server */
  41.     if (connect(sock, (struct sockaddr *) &echoServAddr, sizeof(echoServAddr)) < 0)
  42.         DieWithError("connect() failed");

  43.     echoStringLen = strlen(echoString); /* Determine input length */

  44.     /* Send the string to the server */
  45.     if (send(sock, echoString, echoStringLen, 0) != echoStringLen)
  46.         DieWithError("send() sent a different number of bytes than expected");

  47.     /* Receive the same string back from the server */
  48.     totalBytesRcvd = 0;
  49.     printf("Received: "); /* Setup to print the echoed string */
  50.     while (totalBytesRcvd < echoStringLen)
  51.     {
  52.         /* Receive up to the buffer size (minus 1 to leave space for
  53.            a null terminator) bytes from the sender */
  54.         if ((bytesRcvd = recv(sock, echoBuffer, RCVBUFSIZE - 1, 0)) <= 0)
  55.             DieWithError("recv() failed or connection closed prematurely");
  56.         totalBytesRcvd += bytesRcvd; /* Keep tally of total bytes */
  57.         echoBuffer[bytesRcvd] = '\0'; /* Terminate the */
  58.         printf("%s", echoBuffer); /* Print the echo buffer */
  59.     }

  60.     printf("\n"); /* Print a final linefeed */

  61.     close(sock);
  62.     exit(0);
  63. }



DieWithError.c
C/C++ code
  1. #include <stdio.h> /* for perror() */
  2. #include <stdlib.h> /* for exit() */

  3. void DieWithUserMessage(const char *msg,const char *detail)
  4. {
  5.     fputs(msg,stderr);
  6.     fputs(":",stderr);
  7.     fputs("detail",stderr);
  8.     fputs("\n",stderr);
  9.     exit(1);
  10. }
  11. void DieWithError(char *errorMessage)
  12. {
  13.     perror(errorMessage);
  14.     exit(1);
  15. }

非阻塞的socket
O_NONBLOCK 和O_NDELAY 差不多,但第一个更好,因为返回的是-1,第二个是0,内容的结尾就是0

UNP的16.3和16.4节 介绍了 非阻塞的connect,
利用好error code, errno是一个全局变量,每个线程一个errno,而不是程序(或者准确的说,进程)。C标准中说明了它的规范,由编译器实现。可能由宏定义来实现。
The     integer     errno   is   set   by   system   calls   (and   some   library   functions)   to   indicate   what   went   wrong.
只需要包含 error.h就可以使用,没有显式的定义。

RAW socket:

Raw sockets allow new IPv4 protocols to be implemented in user space. A raw socket receives or sends the raw datagram not including link level headers.

The IPv4 layer generates an IP header when sending a packet unless the IP_HDRINCL socket option is enabled on the socket. When it is enabled, the packet must contain an IP header. For receiving the IP header is always included in the packet.




Linux协议栈:
sys_socketcall

Linux 中的 socket 结构是 struct sock,这个结构是在 linux/include/net/sock.h 中定义的。
阅读(2366) | 评论(0) | 转发(0) |
0

上一篇:defy 使用技巧

下一篇:为什么引入补码

给主人留下些什么吧!~~