简体   繁体   English

服务器连接不同的套接字端口

[英]Server connecting with different sockets port

I have read a question on a mock interview.我读过一个关于模拟面试的问题。 Here is the question...这是问题...

Code a C++ program to connect a server (ex. IP:192.168.10.131) on 2 different sockets on port 2345,4325, simultaneously..编写一个 C++ 程序,同时在端口 2345,4325 上的 2 个不同套接字上连接服务器(例如 IP:192.168.10.131)。

My doubt is wheather it is saying create 2 sockets with common interface ip 192.168.10.131 and port 2345,4325 respectively.我的疑问是它是否在说分别创建 2 个具有公共接口 ip 192.168.10.131 和端口 2345,4325 的套接字。 Or it is saying connect a server having interface ip 192.168.10.131 to two different connection sockets on another server machine on different sockets port..或者说将具有接口 ip 192.168.10.131 的服务器连接到不同套接字端口上另一台服务器机器上的两个不同连接套接字..

If i am guessing first one right then I just need to create two socket connection and start these on individual thread.如果我猜对了第一个,那么我只需要创建两个套接字连接并在单个线程上启动它们。

If 2 nd one is right how i need to do that.... Please help...如果第二个是正确的,我需要怎么做.... 请帮忙...

The simplest interpretation (which is probably correct in the context of an interview, but of course you'd ask) is to create two sockets and connect one to each of the given ports on the given IP address.最简单的解释(在采访中可能是正确的,但您当然会问)是创建两个套接字并将一个连接到给定 IP 地址上的每个给定端口。

A TCP connection is defined by the 4-tuple (source address, source port, destination address, destination port). TCP 连接由四元组(源地址、源端口、目的地址、目的端口)定义。 The source address and port are usually irrelevant to such questions because they'll be chosen automatically by default.源地址和端口通常与此类问题无关,因为默认情况下会自动选择它们。 So when the question says "on 2 different sockets on port 2345,4325" the most likely interpretation is that those are the destination ports from the client's perspective.因此,当问题说“在端口 2345,4325 上的 2 个不同套接字上”时,最可能的解释是从客户端的角度来看,这些是目标端口。

So it's really two calls to socket(2) and two calls to connect(2) with perhaps a sprinkling of other functions like inet_pton(3) .所以它实际上是对socket(2)两次调用和对connect(2)两次调用,可能还有一些其他函数,如inet_pton(3)

As for "simultaneously," yes you could use threads, but a likely better solution is to multiplex them using select(2) .至于“同时”,是的,您可以使用线程,但可能更好的解决方案是使用select(2)对它们进行多路复用。 Being too quick to jump to a multithreaded solution can be a red flag in an interview.过快地跳转到多线程解决方案可能是面试中的一个危险信号。 Again, you'd want to ask about this.再次,你想问这个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM