在Cocoa中运行Socket服务器 [英] Running a Socket Server in Cocoa

查看:163
本文介绍了在Cocoa中运行Socket服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图编写一个程序,使用套接字通过网络连接自身的其他实例。因为最终我想写一个Windows版本,我目前在OS X端使用BSD套接字,以便我可以确保它将与(最终)Windows版本兼容。

I'm trying to write a program that uses sockets to connect with other instances of itself over the network. Since eventually I'd like to write a Windows version as well, I'm currently using BSD sockets on the OS X side so that I can ensure that it will be compatible with the (eventual) Windows version.

我已经能够使这个工作到目前为止的唯一方法是如果我在创建服务器套接字时指定我的实际IP地址。如果我使用127.0.0.1,我只能从我的本地机器连接。

The only way that I've been able to get this to work so far is if I specify my actual IP address when creating the server socket. If I use 127.0.0.1 instead, then I can only connect from my local machine.

虽然这在理论上很好,问题他们变成我怎么知道哪个IP地址要使用?我不知道如何通过Cocoa获取当前机器的IP地址,即使我可以,如果有多个有效的IP地址(例如机场和以太网连接,如果)。我如何知道使用哪一个?我可以问用户,但是这似乎不是他们可以/应该知道的。

While this is fine in theory, the question them becomes how do I know which IP address to use? I'm not sure how to get an IP address for the current machine via Cocoa, and even if I can, what if there are multiple valid IP address (such as both an Airport and ethernet connections, for example). How do I know which one to use? I could ask the user, but that doesn't seem like something they could/should know.

我可以提供我的客户端和服务器连接代码,如果必要,我可以从远程机器连接,我认为问题不在我的代码。

I can provide my client and server connection code if necessary, however given that I am able to make a connection from a remote machine, I'm thinking that the problem isn't in my code.

感谢您的时间。 :)

推荐答案

使用0.0.0.0作为要监听的IP地址。它将侦听所有地址。

Use 0.0.0.0 as the IP address to listen on. It'll listen on all addresses.

可能,在您使用的套接字API中为此地址定义了一个常量。如果您使用标准C套接字API,则为INADDR_ANY。

Probably, a constant is defined for this address in the socket API you are using. If you are using standard C sockets API, it's INADDR_ANY.

这篇关于在Cocoa中运行Socket服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆