Which serial port is Arduino using... from inside Arduino

Is there a way to find out which serial port Arduino is currently using?

For example, if I do

Serial.begin(9600);

and Arduino then connects to COM14... is there a way in the Arduino sketch that I could get this information? Getting the port name as a variable I can use in the sketch?

So I can do something like

if (PortName == "COM14")

No.
The Arduino has a serial port. That's it. It has no way to know what the PC is calling its COM port, unless you enter it into your sketch somehow.

You do not do Serial.begin(9600) and THEN the Arduino connects.

The Arduino is already connected (from both a software and a hardware perspective) before you even do Serial.begin(); exception might be Arduinos that can act as HID.

Also, the COM ports can change (different computer, different com port or multiple arduinos and it might depend on which one was connected first).

Question is why you would need this?

Although the Arduino cannot itself discover what port it is connected to, it should be possible for it to query the PC to find out. However, that would require some specially written software to be running in the PC in order for it to respond to the request for information.

sterretje:
You do not do Serial.begin(9600) and THEN the Arduino connects.

The Arduino is already connected (from both a software and a hardware perspective) before you even do Serial.begin(); exception might be Arduinos that can act as HID.

Also, the COM ports can change (different computer, different com port or multiple arduinos and it might depend on which one was connected first).

Question is why you would need this?

I'm using nodejs to read the com ports and need to somehow identify different arduino boards on it. All I can see that's done in nodejs is that you tell it the ports to read from and then it just gives back data from any port that sends it... it doesn't seem to know exactly what port the data is coming from, unless there's something I'm missing there.

I just want to be able to individually communicate with any given board at any given time. I was hoping I could do it via Arduino sketch but the only method I could think of is to upload a different sketch for each Arduino with a flag the Arduino can include when it sends serial data to nodejs...

But I really want to avoid having to save out a different sketch for each Arduino because it could be hundreds of Arduino boards and I just want one sketch to work for all of them.

No idea about nodejs.

If there is no other solution, the below will work without having to write different sketches.

Option 1
Store a unique ID in eeprom; you can add some code to the sketch so you can give an ID to each Arduino using e.g. the serial port.

Option 2
Add dipswitches to give each Arduino an ID.

With both options, the Arduinos can identify themselves.