0

On a Mac running OS X Yosemite using C, C++, or Objective-C and their respective OS included frameworks, how can I programmatically find the ports currently being listened on, and the names of the applications doing the listening. My research led me to <sys/proc.h> and <sys/proc_info.h>. However, I couldn't see the correct way to do this there (I could have missed something).

Trevor Hickey
  • 36,288
  • 32
  • 162
  • 271
sheeldotme
  • 2,237
  • 14
  • 27
  • 3
    Well, both `lsof` and `netstat` do this sort of thing and their source code is available: [lsof](http://www.opensource.apple.com/source/lsof/lsof-53/lsof/) [netstat](http://www.opensource.apple.com/source/network_cmds/network_cmds-457/netstat.tproj/) – Ken Thomases Dec 30 '14 at 00:00
  • I've looked through the source and wasn't able to find the relevant code, if you're aware of the specific function that does this it would be greatly appreciated. Furthermore, lsof does provide the information I'm looking for on a **Mac**, however netstat doesn't (for all those who find this page). – sheeldotme Jan 02 '15 at 16:18

1 Answers1

1

Rather than copying the netstat code, I recommend calling netstat from your C/C++/Objective C code.

See How do I execute a Shell built-in command with a C function? for details.

Also, man netstat to figure out what parameters you want to narrow your results.

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
WonderMonster
  • 220
  • 3
  • 9
  • 1
    It looks like netstat does not provide the information i'm looking for on mac, only lsof does. Please correct me if I'm wrong but that's what I've found. – sheeldotme Jan 02 '15 at 16:15