当前位置: 技术问答>linux和unix
linux socket programe 同一个IP下 bind 多个socket,可以不??
来源: 互联网 发布时间:2015-02-08
本文导语: setsockpt(,,,),只是不同IP可以bind 多个socket,我要同一个IP下不同端口 bind 多个socket,可以不? | #include #define PortToListen1 8888 #define PortToListen2 9999 int main() { int s1, s2; sockadd...
setsockpt(,,,),只是不同IP可以bind 多个socket,我要同一个IP下不同端口 bind 多个socket,可以不?
|
#include
#define PortToListen1 8888
#define PortToListen2 9999
int main()
{
int s1, s2;
sockaddr_in sa1, sa2;
memset(&sa1, 0, sizeof(sa1));
memset(&sa2, 0, sizeof(sa2));
sa1.sin_family = AF_INET;
sa2.sin_family = AF_INET;
sa1.sin_port = htons(PortToListen1);
sa2.sin_port = htons(PortToListen2);
sa1.sin_addr.s_addr = INADDR_ANY;
sa2.sin_addr.s_addr = INADDR_ANY;
s1 = socket(AF_INET, SOCK_STREAM, 0);
s2 = socket(AF_INET, SOCK_STREAM, 0);
bind(s1, (struct sockaddr *)&sa1, sizeof(sa1));
bind(s2, (struct sockaddr *)&sa2, sizeof(sa2));
...
}
#define PortToListen1 8888
#define PortToListen2 9999
int main()
{
int s1, s2;
sockaddr_in sa1, sa2;
memset(&sa1, 0, sizeof(sa1));
memset(&sa2, 0, sizeof(sa2));
sa1.sin_family = AF_INET;
sa2.sin_family = AF_INET;
sa1.sin_port = htons(PortToListen1);
sa2.sin_port = htons(PortToListen2);
sa1.sin_addr.s_addr = INADDR_ANY;
sa2.sin_addr.s_addr = INADDR_ANY;
s1 = socket(AF_INET, SOCK_STREAM, 0);
s2 = socket(AF_INET, SOCK_STREAM, 0);
bind(s1, (struct sockaddr *)&sa1, sizeof(sa1));
bind(s2, (struct sockaddr *)&sa2, sizeof(sa2));
...
}
|
所谓socket就是:IP+Port,两者之一不同就是不同的SOCKET。