简体   繁体   中英

Running a Socket Server in Cocoa

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.

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.

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.

Thank you for your time. :)

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

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.

There is a network discoverability protocol called Bonjour that you can use to publish your servers on the network and then your clients can automatically connect to them. It's cross platform, but usually called zero-config on other systems.

When doing any kind of socket programming checkout Beej's socket guide. Its been around for ages and covers most of the basics.

http://beej.us/guide/bgnet/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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