Sunday, June 29, 2008

Unix Socket Programming Woes

I just spent a day and a half trying to figure something out.

I think I'm going to buy the late Richard Steven's book, Unix Network Programming: Sockets API because of this. I think if I had that book I could have saved myself some time.

Point is, my problem is that I was trying to set up a dynamically created TCP port, using getsockname() to figure out what that port number was. The trouble was that I kept getting 0 back as the port number, even though I was still able to connect to the host. Any port lower than 1024 (I think it's 1024) is reserved for the Operating System, so I was baffled why it was still working when it shouldn't have.

Solution: call getsockname() AFTER you connect to the host. Then you get the right port #.

I feel like such an idiot. I wish the man pages could give some clue about the right order to call this stuff in. (My fork() calls were so much easier to figure out!)

6 comments:

Gunner said...

When people start talking about partitioning hard drives, and ports, and sockets I start hearing the adult voices in Charlie Brown specials.. WA! WA! WA!...Like a whole nother language.

I want to try linux, but I hear people start talking about drives and such and I have trouble getting simple add-ons to work with my firefox.

Diane Lowe said...

Hi Gunner!

It IS a whole nother language! You have no idea! ;)

I really like Linux as an operating system. It's very stable, but you are working very close to the computer, so to speak. There are GUIs that will emulate the Windows or Mac experience though.

The best thing to do is get an old computer that's just lying around not doing anything and put Linux on that. Then you can play around and no one cares if you accidentally trash everything. Plus you'll learn a lot.

Time Traveller said...

That's the problem with Unix programming, once you're stuck you can spend hours, days, looking for a solution and it's not alwasya obvious what to ask google for either :)

Diane Lowe said...

Hi Time Traveller!

Yes, I have to agree that knowing what to ask google for is a big part of debugging Unix problems. . .and even then sometimes you get no help. :(

Time Traveller said...

Well if you can do it - you can earn the big bucks :) or stick to easy programming like me :)

Diane Lowe said...

Haha!

Apparently, I can do it!

I was told by my class TA I had the best programming project in the class!

Not sure where the big bucks are hiding though . . . .